2017-02-04 58 views
0

如何在球衣资源中自动装配我的spring bean?Spring 4和球衣的编程集成

我想凑齐一个使用spring初始化jax-rs资源中的字段的泽西应用程序。从谷歌搜索,似乎可能,但他们总是空。我的bean被创建,但没有被注入。

我的REST资源

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

    @Autowired 
    private ClipHandler clipHandler; 

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

弹簧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("/"); 
    } 
} 

和bean的配置(注意:我也尝试添加bean来RootConfig

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

    @Bean 
    public ClipHandler clipHandler() { 
    return new ClipHandler(); 
    } 
} 

回答

1

你可以在你的球衣资源中手动调用自动装配,如下所示:

@Context 
private ServletContext servletContext; 

@PostConstruct 
public void init() { 
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, servletContext); 
} 
+0

如果我删除了@ @ Component,那么它就起作用了。我见过一些据称不需要删除的例子。任何想法如何做到这一点? – TedTrippin

+0

似乎替代方案是用户jersey-spring3,从纯粹的角度来看,它不适用于spring4应用程序。 – TedTrippin