我正在開發一個使用Jersey 2的REST API,我需要一些類在啓動時實例化,而不僅僅是當某些資源請求觸發它時。澤西島2中HK2的asEagerSingleton是什麼?
所以我問的是:我如何實現下面定義的SomethingImpl
實例是在服務器啓動時創建的,而不僅僅是當有人點擊某些資源時?在Guice中,我會使用.asEagerSingleton()
。
應用:
public class MyApplication extends ResourceConfig {
public MyApplication() {
register(new AbstractBinder() {
@Override
protected void configure() {
bind(" else").to(String.class);
bind(SomethingImpl.class).to(Something.class).in(Singleton.class);
}
});
register(SomeResource.class);
}
}
東西:
public interface Something {
String something();
}
public class SomethingImpl implements Something {
@Inject
public SomethingImpl(final String something) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println(something() + something);
try {
Thread.sleep(4000);
} catch (final InterruptedException e) {
break;
}
}
}
}).start();
}
@Override
public String something() {
return "Something";
}
}
一些資源:
@Path("/")
public class SomeResource {
private final Something something;
@Inject
public SomeResource(final Something something) {
this.something = something;
}
@GET
@Path("something")
public String something() {
return something.something();
}
}
你就不能創建和綁定SomethingImpl'的'實例,而不是綁定班級類型? – Kapep
在這個簡化的代碼中,是的。但在我真正的代碼中,我需要實例化的類具有幾個注入對象的構造函數。 – Stine