Java Jersey 构造 class 在绑定时

Java Jersey construct class at bind time

我正在研究一些 Java 球衣的东西,我想做以下事情;

我有一个 class 叫做 SerialSubject:

public class SerialSubject{
    private final SomeDatabase someDatabase;

    @Inject
    public SerialSubject(SomeDatabase someDatabase){
        this.someDatabase = someDatabase;
        initializeSerial();
    }

    InitializeSerial(){
        SerialConfig config = SomeDatabase.getConfig();
        //Open a Serial connection using this config
    }
}

我正在使用 AbstractBinder 绑定此 class 并照常将其注册到我的 ResourceConfig。

bind(SerialSubject.class).to(SerialSubject.class).in(Singleton.class)

一切顺利,资源请求时依赖关系已解决,串行连接已打开。

现在警告:我想在启动时打开串行连接。有什么方法可以立即实例化 class 吗?手动构建它不会做,因为需要数据库(已经绑定到 ioc)来检索配置。

您可以使用 Immediate 范围

Immediate is a scope that operates like javax.inject.Singleton scope, except that instances are created as soon as their corresponding Descriptors are added. When the corresponding Descriptor is removed from the locator the Immediate scope service is destroyed. In particular Immediate scope services are not destroyed if the ServiceHandle.destroy() method is called. Care should be taken with the services injected into an immediate service, as they also become virtual immediate services

bind(SerialSubject.class).to(SerialSubject.class).in(Immediate.class)

您还需要配置 ServiceLocator 以启用直接作用域。

public class JerseyApplication extends ResourceConfig {

    @Inject
    public JerseyApplication(ServiceLocator locator) {
        ServiceLocatorUtilities.enableImmediateScope(locator);
    }
}

另请参阅: