Jersey 2 + Spring: @Autowired为空

4
我正在尝试使用Jersey 2和Spring,参考了这篇文章:如何使用Spring IoC容器将Jersey 2集成到项目中。然而,在客户端请求后,自动装配的bean为空。在applicationContext.xml文件中,我只设置了component-scan
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;
    }
}

我做错了什么?
更新:这是我的pom.xml文件https://bitbucket.org/spukhov/memo-ws/src/00724e00e3aa786f62fd0e43fe0606de6ae569df/pom.xml?at=master

你是否使用 component-scan 扫描了正确的包? - yate
@luiggi 这不是重复内容。请证明或留下反馈。 - Reynard
请发布您所做的配置和其他相关信息以复制此问题。 - Luiggi Mendoza
@chrylis 那是针对客户端的,不应该影响服务器端的操作。 - Luiggi Mendoza
1
我不知道为什么它被标记为“离题”。但是可以考虑为“不清楚你在问什么”,因为问题没有很好地阐述问题的背景。 - Jama A.
显示剩余4条评论
2个回答

11

Spring管理的Bean不能直接注入到JAX-RS类中,您需要使用Jersey扩展来将其与Spring集成。

您的pom.xml中缺少一个Maven依赖项。

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

请参考Jersey文档:第22章.Spring DI,页面底部有指向示例Spring集成的Github项目链接。

我在您的项目中还发现了另一个问题,即您没有展示如何加载和配置spring上下文。您需要在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>

1

如果您正在使用基于Java的方法进行Spring配置,您还需要执行以下操作:

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

在您的WebApplicationInitializer实现中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接