Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey 2 + Spring: @Autowired is null

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

like image 553
Reynard Avatar asked Dec 15 '22 19:12

Reynard


2 Answers

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>
like image 58
Jama A. Avatar answered Jan 02 '23 09:01

Jama A.


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

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

in your WebApplicationInitializer implementation

like image 43
Nisarg Panchal Avatar answered Jan 02 '23 09:01

Nisarg Panchal