具有所需构造函数参数的Restlet服务器资源

dje*_*lin 10 java inversion-of-control restlet

在restlet中获取此错误:

ForwardUIApplication ; Exception while instantiating the target server resource.
java.lang.InstantiationException: me.unroll.forwardui.server.ForwardUIServer$UnsubscribeForwardUIResource
Run Code Online (Sandbox Code Playgroud)

我确切知道为什么.这是因为我的构造函数看起来像这样:

public UnsubscribeForwardUIResource(MySQLConnectionPool connectionPool) {
Run Code Online (Sandbox Code Playgroud)

并且Restlet访问资源,如下所示:

router.attach(Config.unsubscribeUriPattern(), UnsubscribeForwardUIResource.class);
Run Code Online (Sandbox Code Playgroud)

问题是我实际上需要那个ctor参数.我怎样才能访问它?(注意我没有使用任何IOC框架,只有很多ctor参数,但这实际上是一个IOC模式).

Tom*_*ros 11

您可以使用上下文将上下文属性传递给资源实例.

ServerResource API doc:

在使用默认构造函数进行实例化之后,将调用最终的Resource.init(Context,Request,Response)方法,设置上下文,请求和响应.您可以通过重写Resource.doInit()方法来拦截它.

所以,在附件时:

router.getContext().getAttributes().put(CONNECTION_POOL_KEY, connectionPool);
router.attach(Config.unsubscribeUriPattern(), UnsubscribeForwardUIResource.class);
Run Code Online (Sandbox Code Playgroud)

在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
}
Run Code Online (Sandbox Code Playgroud)