一:用idea 创建 springboot 项目:
详情请参考:《使用IDEA创建一个springboot项目》
二:具体代码内容:
1:sringboot 整合 listener 方式一:
1:查看效果
1:FirstListener
package com.AlanCode.springBoot.Listener; /** * @author Alan_liu * @Create 2021/2/16 10:58 */ import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; /** *@program: SpringBootAddListtener *@description: springboot 整合 listener 方式一: * * * *传统spring 方式配置 listener 内容: * * <listener> * * <listener-class>com.alancode.springboot.listener.FirstListener</listener-class> * * </listener> * *@author: Alan_Liu *@create: 2021-02-16 10:58 */ @WebListener public class FirstListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("--------------listener.......init.....---------------------------------------"); } @Override public void contextDestroyed(ServletContextEvent sce){ } }2:ListenerApplication
package com.AlanCode.springBoot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; /** * springboot 整合 listener 方式一 * @author Alan_Liu */ @SpringBootApplication @ServletComponentScan public class ListenerApplication { public static void main(String[] args) { SpringApplication.run(ListenerApplication.class, args); } } /*** * * **注意: **关于编写启动器需要注意的问题。 **启动器存放位置:启动器可以和controller 位于同一个包 package下,或者位于controller的上一级包。 **但是不能把该文件放到controller平行级的包或者其子包下。 * ServletComponentScan 含义: * 在springboot 启动时候进行扫描@webServlet注解的所有servlet、filter类。并将该类实例化 * * ***/
3: pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.AlanCode.springBoot</groupId> <artifactId>springBootAddListener</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springBootAddListener</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
----------------------