我有一個自定義的ServletContextListener,用於初始化和啓動Cron4J調度器。在Spring的WebApplicationInitializer中排序監聽器
public class MainListener implements ServletContextListener {
@Value("${cron.pattern}")
private String dealHandlerPattern;
@Autowired
private DealMoqHandler dealMoqHandler;
}
我在自動綁定監聽某些對象,如圖所示,想爲春天來管理聽者的實例。我通過WebApplicationInitializer
使用了編程web.xml配置,但到目前爲止,Listener沒有被自動裝配(每當我嘗試訪問所謂的自動裝配對象時,都是NullPointerExceptions)。
我已經嘗試添加的ContextLoaderListener後添加我的客戶監聽器,如下圖所示:
public class CouponsWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(SpringAppConfig.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
container.addListener(new MainListener()); //TODO Not working
}
我檢查這些過去的問題Spring - Injecting a dependency into a ServletContextListener和dependency inject servlet listener並試圖執行的contextInitialized方法中下面的代碼我聽衆:
WebApplicationContextUtils
.getRequiredWebApplicationContext(sce.getServletContext())
.getAutowireCapableBeanFactory()
.autowireBean(this);
不過,我只是得到以下異常:
Exception sending context initialized event to listener instance of class com.enovax.coupons.spring.CouponsMainListener: java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?
at org.springframework.web.context.support.WebApplicationContextUtils.getRequiredWebApplicationContext(WebApplicationContextUtils.java:90) [spring-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
如何在添加偵聽器之前確保Spring已經完成實例化?
我剛纔在調試時意識到,手動實例化對象不允許Spring自動裝載它,就像你說的那樣。儘管我犯了一個完全不同的錯誤(詳細內容在我的自我回答中)。不過,謝謝你的澄清。 –