Restlet server resource with constructor parameters needed

守給你的承諾、 提交于 2019-12-05 01:34:03

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
}

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

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