SpringBoot上下文初始器加载过程详解
利用 Spring 工厂加载机制,实例化 ApplicationContextInitializer 实现类,并排序对象集合。
关键方法
private <T> Collection<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<>( SpringFactoriesLoader.loadFactoryNames(type, classLoader)); List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names); AnnotationAwareOrderComparator.sort(instances); return instances; }
技术实现步骤
- 实现类: org.springframework.core.io.support.SpringFactoriesLoader
- 配置资源: META-INF/spring.factories
- 排序: AnnotationAwareOrderComparator#sort
自定义初始化器
编写类实现ApplicationContextInitializer接口
有两种指定顺序的方法,第一种:类上加注解@Order(Ordered.HIGHEST_PRECEDENCE),第二种则是实现Ordered接口
@Order(Ordered.HIGHEST_PRECEDENCE) public class HelloWorldApplicationContextInitializer<C extends ConfigurableApplicationContext> implements ApplicationContextInitializer<C> { @Override public void initialize(C applicationContext) { System.out.println("ConfigurableApplicationContext.id = "+ applicationContext.getId()); } }
public class AfterHelloWorldApplicationContextInitializer implements ApplicationContextInitializer, Ordered { @Override public void initialize(ConfigurableApplicationContext applicationContext) { System.out.println("After application.id = " + applicationContext.getId()); } @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE; } }
在spring.properties中配置
# ApplicationContextInitializer
org.springframework.context.ApplicationContextInitializer=\
com.imooc.diveinspringboot.context.AfterHelloWorldApplicationContextInitializer,\
com.imooc.diveinspringboot.context.HelloWorldApplicationContextInitializer
上一篇:java内部类使用总结
栏 目:JAVA代码
下一篇:Java中FilterInputStream和FilterOutputStream的用法详解
本文地址:http://www.codeinn.net/misctech/45063.html
阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机