Sprinboot优雅配置监听,并记录所有启动事件

在阅读Springboot启动源码的时候,发现Springboot自动启动listeners是通过uopeizhi文件配置的,本文就是采用Springboot方式自动装入listeners。

项目依赖



	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.8.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<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>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<finalName>boot</finalName>
	</build>

基于ApplicationListener项目监听配置

这个是Spring的监听在resource目录下建META-INF文件夹,并在该文件夹下面创建spring.factories文件,文件里面配置监听类的全路径,第一行是springboot加载寻找的key,自己的按照如下方式配置即可

org.springframework.context.ApplicationListener=\
boot.Listener.MyListener,\
boot.Listener.DateListener

boot.Listener.MyListener

package boot.Listener;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

public class MyListener implements ApplicationListener<ApplicationEvent>{
	@Override
	public void onApplicationEvent(ApplicationEvent paramE) {
		System.out.println("--------"+paramE.getClass().getName());	
	}
}

启动事件
ApplicationEvent 是顶级的事件抽象接口,所有的事件都继承于此,因此直接监听这个事件就可以得到所有的启动事件

--------**org.springframework.boot.context.event.ApplicationStartedEvent**
--------**org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent**

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.8.RELEASE)

2019-05-21 14:36:56.423  INFO 4120 --- [           main] boot.application                         : Starting application on LIUJP with PID 4120 (started by Administrator in E:\Program Files\wowkSpace\boot)
2019-05-21 14:36:56.435  INFO 4120 --- [           main] boot.application                         : No active profile set, falling back to default profiles: default
--------**org.springframework.boot.context.event.ApplicationPreparedEvent**
2019-05-21 14:36:56.718  INFO 4120 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@21a947fe: startup date [Tue May 21 14:36:56 CST 2019]; root of context hierarchy
2019-05-21 14:37:02.015  INFO 4120 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2019-05-21 14:37:02.062  INFO 4120 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-05-21 14:37:02.078  INFO 4120 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.23
2019-05-21 14:37:02.624  INFO 4120 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-05-21 14:37:02.624  INFO 4120 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 5922 ms
2019-05-21 14:37:03.218  INFO 4120 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2019-05-21 14:37:03.235  INFO 4120 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-05-21 14:37:03.251  INFO 4120 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-05-21 14:37:03.251  INFO 4120 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-05-21 14:37:03.251  INFO 4120 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2019-05-21 14:37:04.469  INFO 4120 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@21a947fe: startup date [Tue May 21 14:36:56 CST 2019]; root of context hierarchy
2019-05-21 14:37:04.725  INFO 4120 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2019-05-21 14:37:04.725  INFO 4120 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2019-05-21 14:37:04.835  INFO 4120 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-05-21 14:37:04.850  INFO 4120 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-05-21 14:37:04.991  INFO 4120 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-05-21 14:37:05.491  INFO 4120 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
--------**org.springframework.context.event.ContextRefreshedEvent**
2019-05-21 14:37:05.716  INFO 4120 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
--------**org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent**
--------**org.springframework.boot.context.event.ApplicationReadyEvent**
2019-05-21 14:37:05.732  INFO 4120 --- [           main] boot.application                         : Started application in 10.546 seconds (JVM running for 11.845)

如上可以看出Springboot启动时间依次 是
1、spring boot启动开始时执行的事件
org.springframework.boot.context.event.ApplicationStartedEvent
2、 对应enviroment已经准备完毕,但此时上下文context还没有创建
org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent
3、上下文context创建完成,但此时spring中的bean是没有完全加载完成的
org.springframework.boot.context.event.ApplicationPreparedEvent
4、spring中的bean是加载完成,刷新ioc容器
org.springframework.context.event.ContextRefreshedEvent
5、spring所有数据准备完成
org.springframework.boot.context.event.ApplicationReadyEvent

监听出处
此文章的监听是模仿springboot的监听配置方法来的,个人用感觉还是注解版的比较好,自己的监听继承ServletContextListener,然后添加@WebListener@Component就可以

	SpringApplication.run(application.class, args);
	
	SpringApplicationRunListeners listeners = getRunListeners(args);

	private SpringApplicationRunListeners getRunListeners(String[] args) {
		Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
		return new SpringApplicationRunListeners(logger, getSpringFactoriesInstances(
				SpringApplicationRunListener.class, types, this, args));
	}

	private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type,
			Class<?>[] parameterTypes, Object... args) {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		// Use names and ensure unique to protect against duplicates
		Set<String> names = new LinkedHashSet<String>(
				SpringFactoriesLoader.loadFactoryNames(type, classLoader));
		List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
				classLoader, args, names);
		AnnotationAwareOrderComparator.sort(instances);
		return instances;
	}

	public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

	public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
		String factoryClassName = factoryClass.getName();
		try {
			Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
					ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
			List<String> result = new ArrayList<String>();
			while (urls.hasMoreElements()) {
				URL url = urls.nextElement();
				Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
				String factoryClassNames = properties.getProperty(factoryClassName);
				result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
			}
			return result;
		}
		catch (IOException ex) {
			throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +
					"] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
		}
	}

SpringApplicationRunListener

基于Spring Boot 启动初始化的过程监听,此处参考大佬的笔记
源于 链接描述

package org.springframework.boot;
public interface SpringApplicationRunListener {
    // 在run()方法开始执行时,就立即调用
    void starting();
    // 当environment构建完成,ApplicationContext创建之前,该方法被调用
    void environmentPrepared(ConfigurableEnvironment environment);
    // 当ApplicationContext构建完成时,该方法被调用
    void contextPrepared(ConfigurableApplicationContext context);
    // 在ApplicationContext完成加载,但没有被刷新前,该方法被调用
    void contextLoaded(ConfigurableApplicationContext context);
    // 在ApplicationContext刷新并启动后,CommandLineRunners和ApplicationRunner未被调用前,该方法被调用
    void started(ConfigurableApplicationContext context);
    // 在run()方法执行完成前该方法被调用
    void running(ConfigurableApplicationContext context);
    // 当应用运行出错时该方法被调用
    void failed(ConfigurableApplicationContext context, Throwable exception);
}

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值