gpt4 book ai didi

java - Jersey 2.17 中的依赖注入(inject)

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:19:42 25 4
gpt4 key购买 nike

我有一个资源类

@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();
}

我尝试了帖子中的答案 Dependency injection with 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)

resourceconfig类是

public class ApplicationConfig extends ResourceConfig {

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

Binder 类是

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");

如何在 Controller 中注入(inject)服务?注入(inject)是对其进行单元测试的首选方法吗(当服务实现时,比如 demoServiceImpl 正在调用另一个服务,比如 XService)并且单元测试不应依赖于 Xservice,因此不应依赖于 demoServiceImpl我如何从测试中将服务模拟注入(inject)到 Controller 中?

最佳答案

在您的第二次尝试中(没有 cdi 依赖项;使用 HK2)您的绑定(bind)不正确。应该是

bind(Implementation).to(Contract)
// - i.e.
bind(DemoServiceImpl.class).to(DemoService.class);

反之亦然。

就测试而言,如果您在同一个包中进行测试(在项目的测试区域中),您应该能够分配该服务,因为它是包私有(private)的。尽管就个人而言,我已经养成了构造函数注入(inject)的习惯。您可以做的另一件事是使用 Jersey Test Framework .你可以看到一个完整的例子here ,其中注入(inject)了模拟服务

关于java - Jersey 2.17 中的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30360060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com