1,通过注解扫描完成Listener组件的注册
- 编写Listener类
编写启动类package com.lxp.Listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; @WebListener public class FristListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent arg0) { } @Override public void contextInitialized(ServletContextEvent arg0) { System.out.println("Listener...Init...."); } }
package com.lxp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import com.lxp.filter.SecondFilter; import com.lxp.servlet.SecondServlet; /** * @author lxp * @date 2018年6月19日 上午11:33:15 * @parameter * @return */ @SpringBootApplication @ServletComponentScan // 方法一:在springBoot启动时会扫描@WebListener,并将该类实例化 public class AppStart { public static void main(String[] args) { SpringApplication.run(AppStart.class, args); } }
2,通过方法完成Listener组件的注册
- 编写Listener类
package com.lxp.Listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class SecondListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("SecondListener...Init....");
}
}
- 编写启动类
package com.lxp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import com.lxp.Listener.SecondListener;
@SpringBootApplication
public class AppStart {
public static void main(String[] args) {
SpringApplication.run(AppStart.class, args);
}
// 方法二:通过方法完成Listener组件的注册
@Bean
public ServletListenerRegistrationBean<SecondListener> getServletListenerRegistrationBean() {
ServletListenerRegistrationBean<SecondListener> bean = new ServletListenerRegistrationBean(new SecondListener());
return bean;
}
}