Jersey 2 + Spring: @Autowired is null

ⅰ亾dé卋堺 提交于 2019-12-17 20:24:34

问题


I'm trying to use Jersey 2 with Spring with help of this article: How to use Jersey 2 with Spring IoC container

But autowired bean is null when the application tries to call it after the client request. In applicationContext.xml i have only component-scan setting.

In pom.xml: 
<spring.version>4.1.0.RELEASE</spring.version>
<jersey.version>2.12</jersey.version>

@Component
@RequestScoped
@Path("/user")
public class UserREST {
    @Autowired
    private UserFacade userFacade;

    @POST
    @Path("/auth")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({MediaType.APPLICATION_JSON})
    public AuthResponse authorize(User user){
        return userFacade.authorize(user);  // Null is caught here
    }
}

-

@Component
public class UserFacade {

    public AuthResponse authorize(com.pushock.model.User user){
        AuthResponse response = new AuthResponse();
        response.setAuthorized(true);
        return response;
    }
}

What am I doing wrong?

UPD: Here is my pom.xml https://bitbucket.org/spukhov/memo-ws/src/00724e00e3aa786f62fd0e43fe0606de6ae569df/pom.xml?at=master


回答1:


Spring managed beans cannot be injected to JAX-RS classes directly, you need to use Jersey extension for integrating it with Spring.

There is a maven dependency which you don't have in your pom.xml

<dependency>
    <groupId>org.glassfish.jersey.ext</groupId>
    <artifactId>jersey-spring3</artifactId>
    <version>2.12</version>
</dependency>

Refer to Jersey Documentation: Chapter 22. Spring DI and at the bottom of the page, there is a link to sample spring integration Github project.

Another problem I've seen in your project is you didn't show how spring context should be loaded and configured. You need to configure it in your web.xml

   <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>



回答2:


and in case you are using java based approach for spring configuration, you also need to :

servletContext.setInitParameter("contextConfigLocation", "<NONE>");

in your WebApplicationInitializer implementation



来源:https://stackoverflow.com/questions/25899226/jersey-2-spring-autowired-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!