Restlet server resource with constructor parameters needed

寵の児 提交于 2019-12-06 19:50:24

问题


Getting this error in restlet:

ForwardUIApplication ; Exception while instantiating the target server resource.
java.lang.InstantiationException: me.unroll.forwardui.server.ForwardUIServer$UnsubscribeForwardUIResource

And I know exactly why. It's because my constructor looks like this:

public UnsubscribeForwardUIResource(MySQLConnectionPool connectionPool) {

And Restlet accesses the resource like so:

router.attach(Config.unsubscribeUriPattern(), UnsubscribeForwardUIResource.class);

Problem is I actually need that ctor argument. How can I make it accessible? (Note I'm not using any IOC framework, just lots of ctor arguments but this is in fact an IOC pattern).


回答1:


You can use the context to pass context atributes to your resource instance.

From the ServerResource API doc:

After instantiation using the default constructor, the final Resource.init(Context, Request, Response) method is invoked, setting the context, request and response. You can intercept this by overriding the Resource.doInit() method.

So, at attachment time:

router.getContext().getAttributes().put(CONNECTION_POOL_KEY, connectionPool);
router.attach(Config.unsubscribeUriPattern(), UnsubscribeForwardUIResource.class);

At your UnsubscribeForwardUIResource class you'll have to move the initialization code from the constructor to de doInit method:

public UnsubscribeForwardUIResource() {
    //default constructor can be empty
}

protected void doInit() throws ResourceException {

     MySQLConnectionPool connectionPool = (MySQLConnectionPool) getContext().getAttributes().get(CONNECTION_POOL_KEY);

    // initialization code goes here
}



回答2:


If you are not using IoC you should do it manually, e.g. you could attach Restlet instance instead of the class. You could use the Context to retrieve attributes.

But maybe it has more sence to utilize a IoC container which will simplify it and reduce boilerplate code, e.g. this is for the Spring: http://pastebin.com/MnhWRKd0



来源:https://stackoverflow.com/questions/15073686/restlet-server-resource-with-constructor-parameters-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!