Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

java - How to register ServletContextListener in spring boot

Hello I'm trying to rewrite my old code to use Spring Boot. I have one listener public class ExecutorListener implements ServletContextListener.

How can I register this listener for Spring Boot? I've tried:

@SpringBootApplication
@ComponentScan
public class Application extends SpringBootServletInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        servletContext.addListener(new ExecutorListener());
    }

}

But the contextInitialized method is not called.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can try couple of things: Register ExecutorListener as a @Bean explicitly:

@Bean
public ExecutorListener executorListener() {
   return new ExecutorListener();
}

or

You can try it with explicitly creating 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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...