我在實作 ServletContextListener 的 TestAppListener 類中嘗試了基于建構式的依賴注入。我收到此錯誤 例外發送背景關系初始化事件到類 [com.example.listener.TestAppListener] 的偵聽器實體。
我搜索了堆疊溢位,但找不到針對這種情況的任何解決方案。請任何人幫我解決這個問題。我也在 META-INF.services 檔案夾中放置了實作類。我的理解是建構式依賴注入存在一些問題,但是我的情況需要這種 DI 方式,因為我想實時在啟動方法中創建資料源連接。
在下面找到我正在使用的所有課程,
@WebListener
public class TestAppListener implements ServletContextListener {
private static TestDao dao;
public TestAppListener(TestDao dao){
this.dao = dao;
}
public TestAppListener(){}
@Override
public void contextInitialized(ServletContextEvent sce) {
dao = ServiceLoader.load(TestDao.class).iterator().next();
dao.startUp();
System.out.println("Context initialized method called");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("Context destroyed method called");
dao.shutDown();
}
}
public interface TestDao {
void startUp();
void shutDown();
}
public class TestDaoImpl implements TestDao {
@Override
public void startUp() {
System.out.println("Database is initialized");
}
@Override
public void shutDown() {
System.out.println("Database is initialized");
}
}
@Configuration
public class SpringConfig {
public SpringConfig() {
}
@Bean
public ServletListenerRegistrationBean<ServletContextListener> listenerRegistrationBean() {
ServletListenerRegistrationBean<ServletContextListener> bean = new ServletListenerRegistrationBean<>();
bean.setListener(new TestAppListener());
return bean;
}
}
uj5u.com熱心網友回復:
更改private static TestDao dao為private final TestDao dao。Spring 不允許將靜態用作注入目標。此外,您的TestDaoImpl類需要是 Spring 組態檔中定義的組件或 bean。
uj5u.com熱心網友回復:
在Servlet @WebListenerS被Servlet容器(Tomcat的/碼頭)當容器開始處理。所以他們對Spring一無所知。
有關更多詳細資訊,請參閱本期討論。
解決方法是將 替換為@WebListenerSpring 的@Component,因此您可以直接將 Spring bean(將您的 Dao 宣告為 spring bean)注入偵聽器。
順便說一句,您必須添加@ServletComponentScanSpring Boot 應用程式類才能激活它。
我創建了一個示例專案來演示@WebServlet,@WebFilter和@WebListener.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/343524.html
上一篇:多載或覆寫equals()方法
