Andrea Colleoni
Andrea Colleoni

Reputation: 6021

Jersey-Spring @Autowired not working

I'm using Jersey-Spring integration to expose business layer services.
In my web.xml I'm using the SpringServlet:

com.sun.jersey.spi.spring.container.servlet.SpringServlet

My business layer is @Component annotated, so I have @Service's using @Repository's provided via Spring's annotation config. Repository's are provided to service's via @Autowired annotation.

If I use a repository through a service using my front end MVC classes everithig goes well, but if I use it through Jersey I get a NullPointerException on the repository object.

The version I'm using (through Maven) are:

Upvotes: 1

Views: 1104

Answers (2)

Gerard
Gerard

Reputation: 71

There is way to solve this problem using the same version mentioned in your question,

If needed ill mention the second way , the first way is to load sring through web.xml like shown below as normal spring confifuration:

<servlet>
    <servlet-name>project-spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:project-spring-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>project-spring</servlet-name>
    <url-pattern>*.htm</url-pattern>
  </servlet-mapping>

Now load your jersey Resources through Application as shown below:

@ApplicationPath("/rest")
public class ResourceLoader extends Application
{

    /* (non-Javadoc)
     * @see javax.ws.rs.core.Application#getClasses()
     */
    @Override
    public Set<Class<?>> getClasses()
    {
        Set<Class<?>> classes = new HashSet<Class<?>>();
        loadResourceClasses(classes);
        return classes;
    }

    private void loadResourceClasses(Set<Class<?>> classes)
    {
        classes.add(StudentResource.class);
    }
}

Then in your resource:

@Path("student")
class StudentResource
{
    private StudentService studentService;

    StudentResource(@Context ServletContext servletContext)
    {
       ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        this.transactionService = applicationContext.getBean(StudentService .class);
    }
}

There'r you go Spring has been configured with all dependency injections with Jersey!!!

Upvotes: 1

fernandospr
fernandospr

Reputation: 3051

You should try using @InjectParam

Upvotes: 0

Related Questions