这是我的 Jersey 配置类
@ApplicationPath("services")
public class JerseyApplication extends ResourceConfig{
public JerseyApplication() {
packages("com.ems");
register(EmployeeService.class);
}
}
此处employeeService
的 Autowiring
给出了空指针异常
@Path("/ems")
@Component
public class EmployeeRestController {
@Autowired
private EmployeeService employeeService;
@GET
@Path("/employees")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Employee> getEmployees() {
return employeeService.getEmployees();
}
}
我已经尝试了一切
在我的 employeeServiceImpl
中,我有 @service 注释
尽管如此,它仍然不起作用。
最佳答案
要使用内置 DI 框架 (HK2) 配置依赖项注入(inject),您应该使用 AbstractBinder
,如 Dependency injection with Jersey 2.0 中的一些答案中所述。 .
@ApplicationPath("services")
public class JerseyApplication extends ResourceConfig {
public JerseyApplication() {
packages("com.ems");
register(new AbstractBinder() {
@Override
protected void configure() {
bind(EmployeeService.class)
.to(EmployeeService.class)
.in(Singleton.class);
}
});
}
}
其次,您不使用@Autowired
注释。这个注解是专门针对Spring的。对于 Jersey 的标准注入(inject),只需使用 @Inject
注释。同时删除 @Component
注释,因为这也适用于 Spring。
顺便说一句,如果您确实想要将 Spring 与 Jersey 集成,您应该阅读 Why and How to Use Spring With Jersey 。它将详细介绍您需要了解的有关集成两个框架的知识。
关于java - Jersey 配置不识别服务和 dao 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52331862/