I am trying to write a small REST application using an embedded Jetty 9 server and a Jersey (2.18) servlet. I would like to use Spring 4 for Dependency Injection, but I am having troubles to inject spring beans in Jersey resources. I am configuring the server programmatically, so no web.xml.
My Jersey resource config is:
public class ApplicationConfig extends ResourceConfig {
public static final String ROOT_PACKAGE = "com.example";
public ApplicationConfig() {
packages(true, ROOT_PACKAGE);
// Features
register(JacksonFeature.class);
property(METAINF_SERVICES_LOOKUP_DISABLE, true);
}
}
The main class (where I'm configuring and starting Jetty) is:
public class Runner {
public static void main(String[] args) {
ApplicationConfig applicationConfig = new ApplicationConfig();
ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(applicationConfig));
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.addServlet(jerseyServlet, "/rest/*");
context.addEventListener(new ContextLoaderListener());
context.addEventListener(new RequestContextListener());
context.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
context.setInitParameter("contextConfigLocation", ProductionSpringConfig.class.getName());
Server server = new Server(8080);
server.setHandler(context);
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The spring configurations is:
@Configuration
@ComponentScan("com.example")
public class ProductionSpringConfig {}
I have added a simple Spring component in the scanned package and I can see it is correctly instantiated when the Server starts:
@Component
public class BeanExample {
public void doSomething(){
System.out.println("HelloWorld");
}
}
When I try to inject it into a Jersey resource though, it is always null. I tried using both the Autowired and Inject annotations. I'm pretty sure I misunderstood something and I didn't configure all the pieces properly.
Could anybody help please?