Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...