如何在Spring Boot中注册ServletContextListener
您好,我正在尝试重写旧代码以使用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
明确:
@Beanpublic ExecutorListener executorListener() {
return new ExecutorListener();
}
要么
您可以通过显式创建ServletRegistrationBean进行尝试:
@Beanpublic 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;
}
以上是 如何在Spring Boot中注册ServletContextListener 的全部内容, 来源链接: utcz.com/qa/402107.html