我正在使用 Jersey 2 开发一个 REST API,我需要在启动时实例化我的一些类,而不仅仅是在某些资源请求触发它时。
所以我要问的是:我如何实现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();
}
}