关于Spring boot部署到独立Tomcat时,Servlet未能注入的问题

前文

在将 spring boot 应用部署到独立的tomcat服务器时,会因为@ServletComponentScan注解不起作用,从而导致以注解形式注入的监听器、过滤器以及 Servlet 注入失败(因为独立Tomcat采用的是容器内建的discovery机制),最终导致项目启动失败,为了避免这一情况,最好以 @Bean 的形式注册相关servlet

示例

注册 Session 监听器

首先实现 HttpSessionListener 来定义一个 session 监听器,注意,这里将不再使用 @WebListener 注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//  @WebListener  // 因为需要在独立的tomcat中部署,所以改为采用ServletListenerRegistrationBean来注册监听器
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);
}
}
}

然后在一个配置类中对定义的监听器类进行注册

1
2
3
4
@Bean
public ServletListenerRegistrationBean sessionHandler() {
return new ServletListenerRegistrationBean<>(new SessionHandler());
}

通过以上方式,可以有效解决 @ServletComponentScan 在独立容器中失效的问题