简体   繁体   English

球衣2 +春季:@Autowired为空

[英]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 我试图在本文的帮助下将Jersey 2与Spring一起使用如何在Spring IoC容器中使用Jersey 2

But autowired bean is null when the application tries to call it after the client request. 但是当应用程序尝试在客户端请求之后调用它时,autowired bean为null。 In applicationContext.xml i have only component-scan setting. 在applicationContext.xml中,我只有组件扫描设置。

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 UPD:这是我的pom.xml https://bitbucket.org/spukhov/memo-ws/src/00724e00e3aa786f62fd0e43fe0606de6ae569df/pom.xml?at=master

Spring managed beans cannot be injected to JAX-RS classes directly, you need to use Jersey extension for integrating it with Spring. Spring托管的bean不能直接注入到JAX-RS类中,您需要使用Jersey扩展将其与Spring集成。

There is a maven dependency which you don't have in your pom.xml 您的pom.xml没有Maven依赖项

<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. 请参阅Jersey文档: 第22章。Spring DI,并且在页面底部,有一个示例Spring集成 Github项目的链接。

Another problem I've seen in your project is you didn't show how spring context should be loaded and configured. 我在您的项目中看到的另一个问题是您没有显示应如何加载和配置spring上下文。 You need to configure it in your web.xml 您需要在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>

and in case you are using java based approach for spring configuration, you also need to : 如果您使用的是基于Java的Spring配置方法,则还需要:

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

in your WebApplicationInitializer implementation 在您的WebApplicationInitializer实现中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM