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).
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
来源:https://stackoverflow.com/questions/15073686/restlet-server-resource-with-constructor-parameters-needed