首页 > 解决方案 > 注入作为单例和 jax-rs 中的请求类

问题描述

我试图在我的 Jaxrs api 中使用注入。
我有一个端点,它运行位于注入类中的一些函数。
到目前为止,一切都很好。我想在我的 api 启动时运行相同的功能,所以我实现了“ContainerLifecycleListener”并添加了与我的端点中相同的代码。我开始出现不在请求范围内的错误。

我的问题是只有在使用单例时才没有错误,后来在使用我的端点时它仍然是单例。
我需要它成为整个应用程序中所有请求的范围。
除了我想成为单身人士的 DB 类。

Class ApiTasks {
       @Inject DB mydb
       @Inject Settings mysettings
   }


Class StartupListener implements ContainerLifecycleListener {
    @Inject ApiTask mytasks

    @Override
    public void onStartup(Container container) {
        mytasks.runtask();
    }
 }

private static class MyCustomInjectionBinder extends AbstractBinder {
   @Override
    protected void configure() {
        // error with not in requested scope
        bind(ApiTasks.class).to(ApiTasks.class).in(RequestScoped.class);
        //// error with not in requested scope
        bind(ApiTasks.class).proxy(true).proxyForSameScope(false).to(ApiTasks.class).in(RequestScoped.class);
        //// works but from this point forward ApiTasks class and its sub injection are singleton . 
        bind(ApiTasks.class).proxy(true).proxyForSameScope(false).to(ApiTasks.class).in(Singlton.class);


    }
}

标签: javadependency-injectionjerseyjax-rs

解决方案


推荐阅读