我有一個資源類依賴注入2.17
@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..);
}
粘合劑類是
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 我將如何注入服務模擬到控制器從測試?
嘗試'@ InjectParam' –