如何在RESTful Web服务资源中允许CDI注入资源? 我正在使用Weld 2(CDI)、Jersey(JAX-RS)和Grizzly(Web服务器)运行标准Java。这是我的简单Web资源:
import training.student.StudentRepository;
import javax.inject.Inject;
import javax.ws.rs.*;
@Path("student")
public class StudentWebResource {
@Inject
private StudentRepository studentRepository;
@GET
@Path("count")
@Produces(MediaType.TEXT_PLAIN)
public Integer getCount() {
return studentRepository.studentCount();
}
}
以下是我如何使用weld启动我的简单Web服务器:
public class Main {
public static void main(String[] args) throws Exception {
startCdiApplication();
}
public static void startCdiApplication() throws Exception {
Weld weld = new Weld();
try {
WeldContainer container = weld.initialize();
Application application = container.instance().select(WebServer.class).get();
application.run();
}
finally {
weld.shutdown();
}
}
}
我怀疑需要修改的代码是通知jersey使用weld进行CDI注入解析的代码:
...
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
public class WebServer implements Application {
/*
* startup the grizzly http server to make available the restful web services
*/
private void startWebServer() throws IOException, InterruptedException {
final ResourceConfig resourceConfig = new ResourceConfig().packages("training.webservice").register(new JacksonFeature());
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(getBaseUri(), resourceConfig);
server.start();
Thread.currentThread().join();
}
...
@Override
public void run() throws IOException, InterruptedException {
startWebServer();
}
}
ContainerInitialized
事件。 - Brice Roncace