我试图将一个单例作用域资源的实例注入到JAX-RS应用程序中,但是当我这样做时,我会得到以下警告信息:
并且
我尝试使用AbstractBinder,但找不到将MyResource的实例绑定到服务的方法。
依赖项:
我有一个应用程序,需要一个已经运行的MyResource实例:警告: 在SERVER运行时注册的提供者com.test.jersey.app.MyResource没有实现在SERVER运行时适用的任何提供者接口。由于约束配置问题,提供者com.test.jersey.app.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的实例绑定到服务的方法。
依赖项:
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.23.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.23.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-jetty-http</artifactId>
<version>2.23.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.23.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.2.19.v20160908</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-util</artifactId>
<version>9.2.19.v20160908</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.2.19.v20160908</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-jmx</artifactId>
<version>9.2.19.v20160908</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
</dependency>
</dependencies>