-1

How do I autowire my spring beans in a jersey resource?

I'm trying to cobble together a jersey app which uses spring to initialise the fields in the jax-rs resources. From googling, it seems possible but they are always null. My beans get created but not injected.

My REST resource

@Path ("/clips")
@Component
public class ClipStreamService {

  @Autowired 
  private ClipHandler clipHandler;

  @GET
  public Response defaultGet() {
    Clip clip = clipHandler.getDefault(); <-- ***** throws an NPE *****

The spring WebInitilizer

public class SpringWebInitialiser implements WebApplicationInitializer {

  @Override
  public void onStartup(ServletContext container) {

    // Create the 'root' Spring application context
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(RootConfig.class);
    rootContext.setServletContext(container);
    container.addListener(new ContextLoaderListener(rootContext));

    // Create the dispatcher servlet's Spring application context
    AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
    dispatcherContext.register(WebConfig.class);

    // Register and map the dispatcher servlet
    ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
  }
}

And the bean config (note I've also tried adding the bean to RootConfig)

@Configuration
@ComponentScan ({ ... })
public class WebConfig {

  @Bean
  public ClipHandler clipHandler() {
    return new ClipHandler();
  }
}
TedTrippin
  • 3,525
  • 5
  • 28
  • 46

1 Answers1

1

You can manually invoke autowiring in your jersey resource like below:

@Context
private ServletContext servletContext;

@PostConstruct
public void init() {
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, servletContext);
}
Monzurul Shimul
  • 8,132
  • 2
  • 28
  • 42
  • If I remove `@Component` then it works. I have seen examples that allegedly don't need it removing. Any ideas how to do that? – TedTrippin Feb 04 '17 at 02:42
  • Seems the alternative is to user jersey-spring3 which isnt ideal for a spring4 app from a pureist point of view. – TedTrippin Feb 04 '17 at 21:13