Jersey配置不识别服务和dao类

问题描述 投票:0回答:2

这是我的泽西配置类

@ApplicationPath("services")
    public class JerseyApplication extends ResourceConfig{
    public JerseyApplication() {

            packages("com.ems");

            register(EmployeeService.class);
        }
    }

这里autowiringemployeeService给出了空指针异常

@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注释仍然,它不工作。

java spring dependency-injection jersey
2个回答
1
投票

要使用内置的DI框架(HK2)配置依赖注入,您应该使用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注释。同时删除@Component注释,因为这也适用于Spring。

顺便说一句,如果你想将Spring与Jersey集成,你应该阅读Why and How to Use Spring With Jersey。它将分解您需要了解的有关集成两个框架的内容。


0
投票

您应该注册Controller而不是Service类。 Sample

@ApplicationPath("services")
    public class JerseyApplication extends ResourceConfig{
    public JerseyApplication() {

            packages("com.ems");

            register(EmployeeRestController.class);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.