2017-02-04 1 views
0

ジャージリソースにSpring Beanをオートワイヤリングする方法を教えてください。Spring 4とジャージのプログラムによる統合

私はjax-rsリソースのフィールドを初期化するためにspringを使用するジャージーアプリケーションを一緒に試してみようとしています。グーグルでは可能ですが、常にnullです。私の豆は作成されますが、注入されません。

私の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設定することができます

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

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

答えて

1

(私もRootConfigにBeanを追加しようとした注意してください)以下のようにあなたのジャージリソースで手動でautowiringを呼び出します:

@Context 
private ServletContext servletContext; 

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

'@ Component'を削除すると動作します。私はそれを削除する必要はないと言われている例を見てきました。任意のアイデアをどのように行うには? – TedTrippin

+0

純粋主義的な観点からspring4アプリには理想的ではないユーザーjersey-spring3に代わるものと思われます。 – TedTrippin

関連する問題