【问题标题】:Jersey 2 + Spring: @Autowired is nullJersey 2 + Spring:@Autowired 为空
【发布时间】:2014-11-12 00:01:00
【问题描述】:

在本文的帮助下,我正在尝试将 Jersey 2 与 Spring 一起使用: How to use Jersey 2 with Spring IoC container

但是当应用程序在客户端请求后尝试调用它时,自动装配的 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 component-scan 已正确设置为根包(一直为我工作)
  • @luiggi 这不是重复的。请证明或留下反馈。
  • 发布您所做的配置和其他相关信息以复制此问题。
  • 我不知道为什么它被标记为“离题”。但它可以被认为是“不清楚你在问什么”,因为问题没有很好的问题背景。

标签: java spring jersey-2.0


【解决方案1】:

如果您使用基于 java 的方法进行 spring 配置,您还需要:

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

在您的 WebApplicationInitializer 实施中

【讨论】:

    【解决方案2】:

    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 文档:Chapter 22. Spring DI,在页面底部,有一个指向sample spring integration 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-23
      • 2015-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多