代码之家  ›  专栏  ›  技术社区  ›  djechlin

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

  •  10
  • djechlin  · 技术社区  · 12 年前

    在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参数。如何使其可访问?(注意,我没有使用任何国际奥委会框架,只是使用了很多ctor论点,但这实际上是一种国际奥委会模式)。

    2 回复  |  直到 12 年前
        1
  •  11
  •   Tomas Narros    12 年前

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

    来自 ServerResource API doc :

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

    因此,在附件时间:

    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
    }
    
        2
  •  1
  •   kan    12 年前

    如果您没有使用IoC,您应该手动执行,例如,您可以附加Restlet实例而不是类。你可以使用 Context 以检索属性。

    但也许它更有意义的是使用IoC容器,这将简化它并减少样板代码,例如这是针对Spring的: http://pastebin.com/MnhWRKd0