您好,我正在尝试重写旧代码以使用Spring Boot。
我有一个侦听器public class ExecutorListener implements ServletContextListener
。
如何为Spring Boot注册此侦听器?
我试过了:
@SpringBootApplication
@ComponentScan
public class Application extends SpringBootServletInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.addListener(new ExecutorListener());
}
}
但是没有调用
contextInitialized
方法。 最佳答案
您可以尝试以下几种方法:
明确将ExecutorListener
注册为@Bean
:
@Bean
public ExecutorListener executorListener() {
return new ExecutorListener();
}
要么
您可以通过显式创建ServletRegistrationBean进行尝试:
@Bean
public DispatcherServlet dispatcherServlet() {
DispatcherServlet servlet=new DispatcherServlet();
servlet.getServletContext().addListener(new ExecutorListener());
return servlet;
}
@Bean
public ServletRegistrationBean dispatcherServletRegistration() {
ServletRegistrationBean registrationBean = new ServletRegistrationBean(dispatcherServlet(), "/rest/v1/*");
registrationBean
.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
return registrationBean;
}