Spring object @Autowired is null in Jersey component

Happy Monday!

Over the weekend I spent a few hours fixing this Jersey/Spring issue. Basically, I am calling Spring Context’s Bean (say, a DAO bean) from within a Jersey Application component.

public class MyRestService {

@Autowired
private GenericDAO genericDAO;

But the autowired DAO object always shows null. The problem is obviously that Jersey context doesn’t properly communicate with Spring application context so the bean is not visible to Jersey. There are many confusing solutions to this problem which fail to help. There is one solution that worked for me is to use ApplicationContextAware interface to allow Jersey to have a handle on the Spring Context. But that “manual bridge” is not very elegant and potentially costly, and verbose to manage. Finally, it turns out Jersey documentation has a good mention to it already that including this dependency in the app will build the bridge between Spring and Jersey.

<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<version>2.21.1</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</exclusion>
</exclusions>
</dependency>

Indeed after I put in this, the NPE disappeared. 🙂

Cheers!

-TY