SpringBoot上下文初始器加载过程详解
程序员文章站
2022-06-09 09:21:38
利用 spring 工厂加载机制,实例化 applicationcontextinitializer 实现类,并排序对象集合。关键方法private collection
利用 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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。