新プロジェクト
これは、POMファイルです
<プロパティ> <のjava.version> 1.8 </java.version> </プロパティ> <依存性> <依存性> <のgroupId> org.springframework.boot </のgroupId> <たartifactId>ばねブートスタータウェブ</たartifactId > </依存> <依存性> <のgroupId> org.springframework.boot </のgroupId> <たartifactId>ばねブートスタータ試験</たartifactId> <スコープ>テスト</スコープ> </依存> </依存関係>
新FirstListenerクラス
FirstListener.java
package com.gongspringlister.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; /** * springBoot 整合 Listener * * <listener> * <listener-class>com.bjsxt.listener.FirstListener</listener-class> *</listener> */ @WebListener public class FirstListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent arg0) { } @Override public void contextInitialized(ServletContextEvent arg0) { System.out.println("Listener...init......"); } }
新建App.java启动类
App.java
package com.gongspringlister; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; /** * springBoot 整合 Listener 方式一 ** * */ @SpringBootApplication @ServletComponentScan public class App { public static void main(String[] args){ SpringApplication.run(App.class,args); } }
运行启动类
SpringBoot 整合 Listener 方式二
新建SecondListener类
SecondListener.java
package com.gongspringlister.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; /** * springBoot 整合 Listener 方式二 * * * */ @WebListener public class SecondListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent arg0) { } @Override public void contextInitialized(ServletContextEvent arg0) { System.out.println("Listener...init......"); } }
编写启动类App2.java
App2.java
package com.gongspringlister; import com.gongspringlister.listener.SecondListener; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.context.annotation.Bean; /** * SpringBoot 整合 Listener 方式二* * * */ @SpringBootApplication public class App2 { public static void main(String[] args){ SpringApplication.run(App2.class,args); } /** * 注册 listener */ @Bean public ServletListenerRegistrationBean<SecondListener> getServletListenerRegistrationBean(){ ServletListenerRegistrationBean<SecondListener> bean= new ServletListenerRegistrationBean<SecondListener> (new SecondListener()); return bean; } }
运行启动类App2.java