在阅读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>
项目监听配置
在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());
}
}
启动日志会记下所有的启动事件
--------**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启动时间依次 是
org.springframework.boot.context.event.ApplicationStartedEvent
org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent
org.springframework.boot.context.event.ApplicationPreparedEvent
org.springframework.context.event.ContextRefreshedEvent
org.springframework.boot.context.event.ApplicationReadyEvent
监听出处
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);
}
}