java - @Autowired 在 Spring 中使用 Jersey 时不起作用

标签 java spring jersey jax-rs

我正在尝试将 Jersey 与 Spring 一起使用。但对于我的一生,我无法弄清楚为什么我的 Spring 依赖项没有被注入(inject)到我的 Rest 类中。

每次我尝试调用 Autowiring 依赖项时,我都会得到 NULL。谁能建议为什么我的依赖项没有被注入(inject)?

我的休息课是这样的:

com.myapp.rest

@Component
@Scope("request") 
@Path("/home")
public class ChartResource {

@Autowired
ChartService chartService;

@GET
@Path("/chart")
@Produces(APPLICATION_JSON)
public Bean getChart() {
        return chartService.retrieveChart();


}

我的 web.xml 文件如下所示

<servlet>
    <servlet-name>myapp</servlet-name>
    <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>org.codehaus.jackson.jaxrs;com.myapp.rest</param-value>
    </init-param>       
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>org.codehaus.jackson.jaxrs</param-value>
    </init-param>   
    <load-on-startup>1</load-on-startup>
</servlet>

我的applicationContext.xml是标准的,指定了组件扫描的基础包:

<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<annotation-driven />
<resources mapping="/resources/**" location="/resources/" />


<context:component-scan base-package="com.myapp" />

</beans:beans>

最佳答案

尝试添加

<context:annotation-config />

我不确定你需要什么才能让 Jersey 的注释正常工作,但是@Autowired是一个 Spring 注释,因此您需要使用 <annotation-config> 的 Spring 版本以便使其正常工作。

关于java - @Autowired 在 Spring 中使用 Jersey 时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10626835/

相关文章:

java - 我们可以在 mapreduce 代码中将一些计算任务放在映射器类的设置方法中吗

java - 在 pdfbox 2.00 中使用 PDFMergerUtility 合并文档

java - 泛型和静态方法

java - 在字符串中查找字符串

Eclipse(spring 工具套件)在服务器启动时自动关闭(包括 Eclipse 日志文件)

java - Jersey REST 请求对象更改

java - ImageIO.read 在字节数组上返回 null

java - 使用 Spring MVC 的 JAXB 注释

java - Spring MVC 不会从 html 表单保存到数据库

java - Restful Web 服务返回 404,错误的 web.xml?