在restlet中获取此错误:
ForwardUIApplication ; Exception while instantiating the target server resource. java.lang.InstantiationException: me.unroll.forwardui.server.ForwardUIServer$UnsubscribeForwardUIResource
我知道为什么.这是因为我的构造函数如下所示:
public UnsubscribeForwardUIResource(MysqLConnectionPool connectionPool) {
Restlet访问资源,如下所示:
router.attach(Config.unsubscribeUriPattern(),UnsubscribeForwardUIResource.class);
问题是我真的需要这个ctor参数.如何使其可访问? (注意,我没有使用任何IOC框架,只是很多ctor参数,但实际上这是一个IOC模式).
解决方法
您可以使用上下文传递资源实例的上下文属性.
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.
所以,在附件时间:
router.getContext().getAttributes().put(CONNECTION_POOL_KEY,connectionPool); router.attach(Config.unsubscribeUriPattern(),UnsubscribeForwardUIResource.class);
在您的UnsubscribeForwardUIResource类中,您必须将构造函数中的初始化代码移动到de doInit方法:
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 }