我正在尝试将一个资源实例注入到具有Singleton范围的JAX-RS应用程序中,但是当我这样做时,我得到:
WARNING: A provider com.test.jersey.app.MyResource registered in SERVER runtime does not implement any provider interfaces applicable in the SERVER runtime. Due to constraint configuration problems the provider com.test.jersey.app.MyResource will be ignored.
我有一个如下应用程序,需要一个已经运行的MyResource实例:
public class MyApp extends ResourceConfig {
public MyApp(MyResource res) {
super(
MyService.class
);
registerInstances(res);
}
}
和
public class MyResource {
String instanceVar;
public MyResource(String test) {
instanceVar = test;
}
public String getString() {
return instanceVar;
}
}
有服务:
@Path("/service")
public class MyService {
@GET
@Path("")
public String get(@Context MyResource res) {
String output;
if (res != null) {
output = res.getString();
} else {
output = "NOT SET";
}
return "output: " + output;
}
}
这是使用以下运行:
public static void main(String[] args) {
MyResource resource = new MyResource("foo");
MyApp restApp = new MyApp(resource);
ServletHolder servlet = new ServletHolder(new ServletContainer(restApp));
Server jettyServer = new Server(8080);
ServletContextHandler context = new ServletContextHandler(jettyServer,"/*");
context.addServlet(servlet,"/*");
try {
jettyServer.start();
jettyServer.join();
} catch (Exception e) {
e.printStackTrace();
} finally {
jettyServer.destroy();
}
}
我尝试使用AbstractBinder,但找不到将MyResource实例绑定到服务的方法.
依赖关系:
最佳答案
使用DI系统使其可注射
原文链接:https://www.f2er.com/java/437351.htmlfinal MyResource resource = new MyResource(...);
final AbstractBinder binder = new AbstractBinder() {
@Override
public void configure() {
bind(resource).to(MyResource.class);
}
};
final MyApp app = new MyApp();
app.register(binder);
也可以看看: