前文
在將 spring boot 應(yīng)用部署到獨立的tomcat服務(wù)器時,會因為@ServletComponentScan注解不起作用,從而導(dǎo)致以注解形式注入的監(jiān)聽器、過濾器以及 Servlet 注入失?。ㄒ驗楠毩omcat采用的是容器內(nèi)建的discovery機制),最終導(dǎo)致項目啟動失敗,為了避免這一情況,最好以 @Bean 的形式注冊相關(guān)servlet
示例
注冊 Session 監(jiān)聽器
首先實現(xiàn) HttpSessionListener 來定義一個 session 監(jiān)聽器,注意,這里將不再使用 @WebListener 注解
// @WebListener // 因為需要在獨立的tomcat中部署,所以改為采用ServletListenerRegistrationBean來注冊監(jiān)聽器
public class SessionHandler implements HttpSessionListener {
@Resource
private ILoginLogService loginLogService;
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
System.out.println("session created");
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
System.out.println("session Destroyed");
UserDetailsBean user = (UserDetailsBean) httpSessionEvent.getSession().getAttribute("user-detail");
if (user != null && loginLogService != null) {
LoginLog lastLogByUserId = loginLogService.getLastLogByUserId(user.getId());
lastLogByUserId.setLogoutTime(new Date());
loginLogService.update(lastLogByUserId);
}
}
}
然后在一個配置類中對定義的監(jiān)聽器類進行注冊
@Bean
public ServletListenerRegistrationBean sessionHandler() {
return new ServletListenerRegistrationBean<>(new SessionHandler());
}
通過以上方式,可以有效解決 @ServletComponentScan 在獨立容器中失效的問題