Jersey 2.17中的依赖注入

3
我有一个资源类
@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();
    }

我尝试了这篇帖子中的方法:Jersey 2.0的依赖注入
如果我使用:
compile group: "org.glassfish.jersey.ext.cdi" , name: "jersey-cdi1x" , version: "2.17"
compile group: "org.glassfish.jersey.ext.cdi" ,name: "jersey-weld2-se" , version: "2.17"

在启动服务器时,我遇到了以下问题:
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)

资源配置类是指用于配置应用程序中的资源的类。
public class ApplicationConfig extends ResourceConfig {

  public ApplicationConfig() {
    register(new ApplicationBinder());
    packages(..name of packages..);
  }

The binder class is

public class ApplicationBinder extends AbstractBinder{
  @Override
  protected void configure() {
      bind(DemoService.class).to(DemoServiceImpl.class);
  }
 }

我使用内嵌模式的Tomcat并添加了初始化参数。
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。 从测试中如何将服务的Mock注入控制器?

1个回答

3
在您的第二次尝试中(没有使用CDI依赖项;使用HK2),您的绑定不正确。应该是:
bind(Implementation).to(Contract)
// - i.e.
bind(DemoServiceImpl.class).to(DemoService.class);

你的理解是相反的。
就测试而言,如果你在同一包中拥有测试(在项目的测试区域),你应该能够分配服务,因为它是包私有的。不过个人而言,我已经养成了构造函数注入的习惯。另一件事情是使用Jersey Test Framework。你可以在这里看到一个完整的示例,其中注入了模拟服务。

请问如何在JerseyTest中注入依赖项?这里有一个相关的stackoverflow链接:https://dev59.com/oovda4cB1Zd3GeqPfOHp - rakesh99

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接