seedhead
seedhead

Reputation: 3805

@Autowired doesn't work when using Jersey with Spring

I am trying to use Jersey with Spring. But for the life of me, I can't figure out why my Spring dependencies aren't being injected into my Rest Class.

Each time I try and invoke the autowired dependency I get NULL. Can anyone suggest why my dependency isn't being injected?

My Rest Class looks like this:

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();


}

My web.xml file looks like this

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

My applicationContext.xml is standard, and specifies the base package for component scanning:

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

Upvotes: 2

Views: 6162

Answers (2)

seedhead
seedhead

Reputation: 3805

Ok - silly question. My applicationContext wasn't being loaded and so it wasn't picking up the package I defined for component scanning!

Upvotes: 1

Chris Thompson
Chris Thompson

Reputation: 35598

Try adding

<context:annotation-config />

I'm not sure what you'll need to get Jersey's annotations to work, but @Autowired is a Spring annotation so you'll need to use the Spring version of <annotation-config> in order to get that to work properly.

Upvotes: 2

Related Questions