Java 泽西岛依赖注入2.17
我有一门资源课Java 泽西岛依赖注入2.17,java,jax-rs,cdi,jersey-2.0,Java,Jax Rs,Cdi,Jersey 2.0,我有一门资源课 @Path("/rest") public class DemoResourceController { @Inject DemoService demoService; @Path("/get/demo") @GET @Produces(APPLICATION_JSON) public Response getDemoLists() { List<String> demoList=demoServic
@Path("/rest")
public class DemoResourceController {
@Inject
DemoService demoService;
@Path("/get/demo")
@GET
@Produces(APPLICATION_JSON)
public Response getDemoLists() {
List<String> demoList=demoService.getDemoList();
return Response.ok(demoList).build();
}
在启动服务器时,我得到
org.jboss.weld.exceptions.IllegalArgumentException: WELD-001408:
Unsatisfied dependencies for type demoService with qualifiers @Default
[BackedAnnotatedField] @Inject DemoResourceController.demoService at injection point
如果我删除了上面的依赖项,那么
javax.servlet.ServletException: A MultiException has 3 exceptions. They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no
object available for injection at SystemInjecteeImpl(requiredType=DemoService,parent=DemoResourceController,qualifiers={},position=- 1,optional=false,self=false,unqualified=null,1952079126)**
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of DemoResourceController errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on package.DemoResourceController
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:421)
resourceconfig类是
public class ApplicationConfig extends ResourceConfig {
public ApplicationConfig() {
register(new ApplicationBinder());
packages(..name of packages..);
}
活页夹类是
public class ApplicationBinder extends AbstractBinder{
@Override
protected void configure() {
bind(DemoService.class).to(DemoServiceImpl.class);
}
}
我在嵌入式模式下使用tomcat并添加init参数
Context ctx = tomcat.addContext("/", new File("web-app").getAbsolutePath());
Wrapper wrapper = ctx.createWrapper();
wrapper.addInitParameter("javax.ws.rs.Application","xx.xx.ApplicationConfig");
如何将服务注入控制器?
注入是单元测试它的首选方式吗(当服务实现调用另一个服务时,比如demoServiceImpl调用另一个服务时,比如说XService),单元测试不应该依赖于XService,因此demoServiceImpl
如何从测试中将服务的模拟注入控制器?在您的第二次尝试中(没有cdi依赖项;使用HK2),您的绑定不正确。应该是
bind(Implementation).to(Contract)
// - i.e.
bind(DemoServiceImpl.class).to(DemoService.class);
你的情况正好相反
就测试而言,如果您在同一个包(在项目的测试区域)中有测试,您应该能够分配服务,因为它是包私有的。虽然就我个人而言,我已经养成了构造函数注入的习惯。你可以做的另一件事是使用。您可以看到一个完整的示例,其中注入了模拟服务您能在这里回答如何在JerseyTest中注入依赖项吗
bind(Implementation).to(Contract)
// - i.e.
bind(DemoServiceImpl.class).to(DemoService.class);