ConfigurationClassPostProcessor
1、它是干什么作用的?
首先这个类处于的位置:org.springframework.context.annotation.ConfigurationClassPostProcessor
它是用来解析我们的配置类的,如果你类上面加入了@Configuration,@CompentScan等,它就会你的这些配置解析出来
2、它是如果实现功能的?
示例代码
public class Main1 {
public static void test1(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();// line1
applicationContext.register(AppConfig.class);// line2
applicationContext.refresh();// line3
}
public static void main(String[] args) {
test1();
}
}
@Configuration
@ComponentScan("com.dh")
public class AppConfig {
}
2.1、Spring什么时候即将ConfigurationClassPostProcessor加入的
示例代码中写了一个Main1和一个AppConfig,Main1主要用于我们测试,AppConfig作为配置类并注册到Spring当中。
注意:
我们此处new AnnotationConfigApplicationContext(AppConfig.class)和new以后applicationContext.register(AppConfig.class);效果是一样的
断点进入line1
public AnnotationConfigApplicationContext() {
/* 初始化AnnotatedBeanDefinitionReader,注意这里传入了一个Bean的registry(Bean注册器)。这个注册器其实就是本类,本类即是Context,也是Registry */
this.reader = new AnnotatedBeanDefinitionReader(this); // line1
this.scanner = new ClassPathBeanDefinitionScanner(this); // line2
}
这里初始化了一个Reader和一个Scanner,不过需要注意,构造方法需要的是BeanDefinitionRegistry,而我们的AnnotationConfigApplicationContext的父类GenericApplicationContext已经实现了BeanDefinitionRegistry接口的,其他的这两个是干啥的暂且不论
断点进去line1
再点进this的方法里面去:
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
/* 赋值BeanRegistry到自己的属性上 */
this.registry = registry;
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
/* 注册一些BeanPostProcessor和配置的类,例如BeanPostProcessor的执行顺序比较器 */
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry); // line1
}
断点进去line1
再进入registerAnnotationConfigProcessors方法:
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
/* 如果当前registry类型==DefaultListableBeanFactory,那么这个BeanFactory就是当前的registry,否则如果registry==GenericApplicationContext,则获取默认创建的beanfactory,再否则就是null了 */
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry); // line0,拿到了BeanFactory
if (beanFactory != null) {
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
/* 主要是解析@Order和@Priority,用做于BeanPostProcessor执行时的顺序排序操作 */
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
/* ContextAnnotationAutowireCandidateResolver提供处理延迟加载的功能 */
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
}
}
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
/* 这里需要理解每个类的类型,将一些默认的BeanDefinition方寸 */
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class); // line1======重点重点重点重点重点重点重点重点
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition();
try {
def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
AnnotationConfigUtils.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
}
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
}
return beanDefs;
}
注意查看:line1的位置,
这里面new了一个RootBeanDefinition,关于BeanDefinition的概念请自行百度(其实BeanDefinition就是Spring用于对我们存在Spring容器内类的信息的描述),这里RootBeanDefinition是sprng内置的BeanDefinition,
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
其中这一行代码中registerPostProcessor的作用是组装成BeanDefinitionHolder然后返回,返回后再add到beanDefs中去。
至此我们看到了spring是何时在何处将ConfigurationClassPostProcessor加入的。
注意:line0处获取到了我们的BeanFactory,class为:DefaultListableBeanFactory,而实际上创建BeanFactory的地方在AnnotationConfigApplicationContext的父类org.springframework.context.support.GenericApplicationContext#GenericApplicationContext()的这个构造方法当中。
2.2、如何将我们的配置类加入到Spring中的
定位debug到示例代码中的line2位置
进入这行方法
public void register(Class<?>... annotatedClasses) {
Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified");
this.reader.register(annotatedClasses);// line1
}
Assert.notEmpty就是一个判空的方法,不管它,下line1
进入line1
public void register(Class<?>... annotatedClasses) {
/* 此处可能有多个类,循环的registerBean */
for (Class<?> annotatedClass : annotatedClasses) {
registerBean(annotatedClass); // line1
}
}
因为可以传入多个class,所以这里是循环的,但我们目前只传了一个AppConfig.class,所以只循环一次,进入line1
进入line1
再进入doRegisterBean方法,就看到如下代码:
void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
/* 将当前的这个类放入到BeanDefinition中,注意此处是Annotated的,所以注册进来的这个类必须带有注解,如果不带有注解则不会被后续解析的 */
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
/* 判断是否需要解析。该类上没有注解的时候则不处理,直接return掉 */
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {// line1
return;
}
abd.setInstanceSupplier(instanceSupplier);
/* 拿到Scope注解的内容 */
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
/* 给BeanDefinition设置scope,注意默认是singleton的 */
abd.setScope(scopeMetadata.getScopeName());
/* 获取BeanName,这个方法时可以执行Bean的名称的,如果没有指定,则生成一个 */
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
/* 解析一些通用的注解,如果存在则设置到BeanDefinition中去,例如@Primary、@Lazy等 */
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
if (qualifiers != null) {
for (Class<? extends Annotation> qualifier : qualifiers) {
if (Primary.class == qualifier) {
abd.setPrimary(true);
}
else if (Lazy.class == qualifier) {
abd.setLazyInit(true);
}
else {
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
customizer.customize(abd);
}
/* 将BeanName和BeanDefinition组装到BeanDefinitionHolder中去 */
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
/* 将beandefinition和beanName放入到分别对应的集合中 */
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry); // line2
}
重点看line1和line2。
line1作用在于如果我们的AppConfig没有注解,那么就不进行后续的操作,直接return了。
line2作用在于如果将我们的BeanDefinition存入到Spring专门放置BeanDefinition的集合中。
注意,doRegisterBean方法当前是在AnnotatedBeanDefinitionReader中,也就是2.1当中第一部代码的line1的位置,注意当时new AnnotatedBeanDefinitionReader的时候传入的this就是我们本身AnnotationConfigApplicationContext
进入BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// Register bean definition under primary name.
String beanName = definitionHolder.getBeanName();
/* 注册Bean,注意这里的registry也是context */
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); // line1
/* 别名 */
// Register aliases for bean name, if any.
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}
注意看line1的位置,这里使用registry(也就是我们的AnnotationConfigApplicationContext)的registerBeanDefinition方法进行注册BeanDefinition。
我们进入到AnnotationConfigApplicationContext的父类GenericApplicationContext的registerBeanDefinition方法中:org.springframework.context.support.GenericApplicationContext#registerBeanDefinition
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
this.beanFactory.registerBeanDefinition(beanName, beanDefinition); // line1
}
line1处使用BeanFactory的registerBeanDefinition方法加入BeanDefinition,我们代码定位到org.springframework.beans.factory.support.DefaultListableBeanFactory#registerBeanDefinition,至于为什么是DefaultListableBeanFactory,请看上方2.1的结尾处有说明:
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
Assert.hasText(beanName, "Bean name must not be empty");
Assert.notNull(beanDefinition, "BeanDefinition must not be null");
...........很多代码
BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
if (existingDefinition != null) {
...........很多代码
this.beanDefinitionMap.put(beanName, beanDefinition);
}
else {
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
synchronized (this.beanDefinitionMap) {
this.beanDefinitionMap.put(beanName, beanDefinition);
...........很多代码
}
}
else {
// Still in startup registration phase
this.beanDefinitionMap.put(beanName, beanDefinition);
this.beanDefinitionNames.add(beanName);
...........很多代码
}
this.frozenBeanDefinitionNames = null;
}
if (existingDefinition != null || containsSingleton(beanName)) {
resetBeanDefinition(beanName);
}
else if (isConfigurationFrozen()) {
clearByTypeCache();
}
}
这里面有很多校验的代码,我们不进行深究,所以我给去掉了,注意看this.beanDefinitionMap.put(beanName, beanDefinition);这一行,这一行就是将我们的类的名称和BeanDefinition放入一个集合中,这个集合的样子如下:
/** Map of bean definition objects, keyed by bean name */
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
除此之外它还会将类的名称放入一个集合中,this.beanDefinitionNames.add(beanName);,这个装类名称的集合样子如下:
/** List of bean definition names, in registration order */
private volatile List<String> beanDefinitionNames = new ArrayList<>(256);
至此我们看到了它是如何将我们的自己的配置类的信息存入到了Spring。
2.3、它是如果拿到和解析我们的配置类
进入到示例代码的line3处:
applicationContext.refresh();
你可能疑惑为什么要调用这一行代码,这一行代码是刷新上下文,spring中很多功能都是在这个方法里面去实现的,如果我们示例代码中line1是这样写的:
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
那么它的构造方法就会如下:
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this();
register(annotatedClasses);
refresh();
}
你应该能发现,我们示例代码中是把这个register和refresh拆分出来自己去调用了,而不是用这个构造器自己去调用。
断点进入refresh方法
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.,准备提前工作,例如设置一些标志位,开始时间等
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.,获取BeanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.,做一些Bean的准备工作
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 空方法
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 到此处的时候,this.BeanFactory的beanDefinitionMap中已经存在的BeanDefinitionMap为预制的,如果我们提前register了,那么此处也会存在
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.注册BeanPostProcessor
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
这里面我们不会去详细解释每一个方法,我后面会出专门针对每一个方法的解释文章。
我们重点看invokeBeanFactoryPostProcessors方法,这是本次随笔的关键。
invokeBeanFactoryPostProcessors
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());// line1
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
getBeanFactoryPostProcessors()这行代码是获取我们自定义的BeanFactoryPostProcessor。
附:
什么是BeanFactoryPostProcessor?
我们进入到这个接口中会发现,此中有postProcessBeanFactory方法,如果我们创建一个类实现于postProcessBeanFactory的话,那么在类的信息组装完成后来调用我们实现此接口的postProcessBeanFactory方法,我们可以在这里面进行其他的操作,举例ConfigurationClassPostProcessor就是实现了BeanFactoryPostProcessor接口,然后它在这个方法里面去看容器中是否有类是配置类,如果有,则解析配置信息,然后解析后对beanFactory进行其他操作,这里的其他操作例如解析到CompentScan,然后拿到扫描包下的类,然后自己组装后放入到beanFactory中,那这样岂不是就是实现了扫描包?
进入line1
line1
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// ==============================第一部分==============================
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>();
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
/* 此处判断我们自己自定义的BeanPostProcessor是否为BeanDefinitionRegistryPostProcessor类型的,如果是,那么则直接执行以下,否则就到后面去执行默认自带的BeanDefinitionRegistryPostProcessor */
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
/* 判断BeanPostProcessor的类型是否为BeanDefinitionRegistryPostProcessor,但注意它的类型一定为BeanFactoryPostProcessor */
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
// ==============================第一部分结束==============================
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.这个就是一个临时的List用来存放找到的内置的BeanDefinitionRegistryPostProcessor
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// BeanDefinitionRegistry
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.拿到所有实现BeanDefinitionRegistryPostProcessor接口的BeanFactoryPostProcessor,并放置到currentRegistryProcessors中
// ==============================第二部分==============================
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
// ==============================第二部分结束==============================
/** 对Processor进行排序,该排序规则对象的设置位置为:
* org.springframework.context.annotation.AnnotationConfigUtils.registerAnnotationConfigProcessors(org.springframework.beans.factory.support.BeanDefinitionRegistry, java.lang.Object)
* beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
* 此时currentRegistryProcessors中存放的时spring内置的,registryProcessors本身放置的是我们自定义的,需要将两个给合并起来
*/
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
/* 去调用实现了BeanDefinitionRegistryPostProcessor接口的BeanFactoryPostProcessor,
* 此中是为了做一些初始化以前bean工厂需要做的事情,使用回调的方法操作不仅可以增加扩展性,还可以便于维护
* */
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();/* 清除list */
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();
}
我们先看第一部分,第一部分中主要做的事情是将我们自定义的BeanFactoryPostProcessor执行一次。
第二部分中,通过类型从Factory中拿到实现了BeanDefinitionRegistryPostProcessor接口的bean的名称,然后循环的将BeanDefinition存入到currentRegistryProcessors集合中。我们的ConfigurationClassPostProcessor就存在于currentRegistryProcessors中
然后下一行代码中:sortPostProcessors(currentRegistryProcessors, beanFactory);这个是将我们的集合进行一个排序,如果多个BeanDefinitioRegistryPostProcessor的话则需要决定其执行先后顺序,
再到下面的第二行代码中:invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);这个方法就是去调用我们的currentRegistryProcessors集合中的BeanFactoryPostProcessor了,进入这个方法。
/**
* Invoke the given BeanDefinitionRegistryPostProcessor beans.
*/
private static void invokeBeanDefinitionRegistryPostProcessors(
Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {
for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
postProcessor.postProcessBeanDefinitionRegistry(registry);
}
}
进入到postProcessor.postProcessBeanDefinitionRegistry(registry);方法中。
就会进入到ConfigurationClassPostProcessor实现的postProcessBeanDefinitionRegistry方法中去。
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
int registryId = System.identityHashCode(registry);
if (this.registriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
}
if (this.factoriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + registry);
}
this.registriesPostProcessed.add(registryId);
processConfigBeanDefinitions(registry); // line1
}
进入到line1中
/**
* Build and validate a configuration model based on the registry of
* {@link Configuration} classes.
*/
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
String[] candidateNames = registry.getBeanDefinitionNames();/*获取所有BeanDefinition中的Bean的名称*/ // line1
for (String beanName : candidateNames) {
BeanDefinition beanDef = registry.getBeanDefinition(beanName);/* 循环拿到所有的BeanDefiniton */ // line2
if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) || /* 判断该类是否已经加载过,如果已经加载过,那么则打一个log */ // line3
ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
/* 说明此类已经加载过,无需再加载 */
if (logger.isDebugEnabled()) {
logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
}
}
/* 如果没加载过,那么判断此类是否是配置类,如果是则加入到configCandidates中后面会对这些配置类进行解析, */
else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) { // line4
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
}
// 如果配置类一个都没有,那就没必要继续往下一步走了
if (configCandidates.isEmpty()) { // line5
return;
}
// Sort by previously determined @Order value, if applicable,对前面解析出来带有Configration相关的集合排序,此排序值取决于该这些类上面放置的@Order注解
configCandidates.sort((bd1, bd2) -> { // line6
int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
return Integer.compare(i1, i2);
});
// Detect any custom bean name generation strategy supplied through the enclosing application context,如果我们设置了BeanName生成器,那么则使用我们的,否则就使用Spring内置的
SingletonBeanRegistry sbr = null;
if (registry instanceof SingletonBeanRegistry) {
sbr = (SingletonBeanRegistry) registry;
if (!this.localBeanNameGeneratorSet) {
BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
if (generator != null) {
this.componentScanBeanNameGenerator = generator;
this.importBeanNameGenerator = generator;
}
}
}
if (this.environment == null) {
this.environment = new StandardEnvironment();
}
// Parse each @Configuration class
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates); // line7
Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
do {/* 解析这些类 */
parser.parse(candidates); // line8
parser.validate();
Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
configClasses.removeAll(alreadyParsed);
// Read the model and create bean definitions based on its content
if (this.reader == null) {
this.reader = new ConfigurationClassBeanDefinitionReader(
registry, this.sourceExtractor, this.resourceLoader, this.environment,
this.importBeanNameGenerator, parser.getImportRegistry());
}
this.reader.loadBeanDefinitions(configClasses);
alreadyParsed.addAll(configClasses);
candidates.clear();
if (registry.getBeanDefinitionCount() > candidateNames.length) {
String[] newCandidateNames = registry.getBeanDefinitionNames();
Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
Set<String> alreadyParsedClasses = new HashSet<>();
for (ConfigurationClass configurationClass : alreadyParsed) {
alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
}
for (String candidateName : newCandidateNames) {
if (!oldCandidateNames.contains(candidateName)) {
BeanDefinition bd = registry.getBeanDefinition(candidateName);
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
!alreadyParsedClasses.contains(bd.getBeanClassName())) {
candidates.add(new BeanDefinitionHolder(bd, candidateName));
}
}
}
candidateNames = newCandidateNames;
}
}
while (!candidates.isEmpty());
......省略了一些代码
}
line1中:从beanFactory中获取到所有BeanDefinition的bean名称
line2中:根据当前循环的beanName的BeanDefinition
line3中:如果这个类已经被加载过,则就打个log,没加载过则进入else中
line4中:判断这个类是不是配置类,如果是则存入configCandidates集合中去,我们进入到ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)这个方法中去。为了防止排版太混乱,我就直接在代码里面进行注释形式的解释
public static boolean checkConfigurationClassCandidate(BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {
// 拿到当前类的全包名。例如现在的这个是com.dh.config.AppConfig
String className = beanDef.getBeanClassName();
// 基础判个空
if (className == null || beanDef.getFactoryMethodName() != null) {
return false;
}
// 创建AnnotationMetadata变量用来存储下面获取到的元信息,元信息就是我们类的一些信息,例如类名、有哪些注解,有哪些方法,有哪些字段等等
AnnotationMetadata metadata;/* 此处需要拿到该BeanDefinition的metadata信息,但由于注解BeanDefinition、XML的BeanDefinition获取metadata的方式不一样,所以需要分别判断其类型后再获取*/
/**
* 下面为什么要判断BeanDefinition的类型呢?
* 因为需要有些不同的BeanDefinition实现类获取元信息metadata的方法不一样,所以得这样干
*/
if (beanDef instanceof AnnotatedBeanDefinition &&
className.equals(((AnnotatedBeanDefinition) beanDef).getMetadata().getClassName())) {
// Can reuse the pre-parsed metadata from the given BeanDefinition...
metadata = ((AnnotatedBeanDefinition) beanDef).getMetadata();
}
else if (beanDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDef).hasBeanClass()) {
// Check already loaded Class if present...
// since we possibly can't even load the class file for this Class.
Class<?> beanClass = ((AbstractBeanDefinition) beanDef).getBeanClass();
metadata = new StandardAnnotationMetadata(beanClass, true);
}
else {
try {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className);
metadata = metadataReader.getAnnotationMetadata();
}
catch (IOException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Could not find class file for introspecting configuration annotations: " + className, ex);
}
return false;
}
}
/* 判断是否加了@Configuration注解 */
if (isFullConfigurationCandidate(metadata)) {
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);/*设置标志位*/
}/* 如果该类为一个接口,那么false,否则判断其是否包含如下注解:@Import、@Component、@ImportResource、@ComponentScan、方法上是否包含@Bean */
else if (isLiteConfigurationCandidate(metadata)) {
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);/*设置标志位*/
}
else {
return false;
}
// 如果排序了,则设置排序标志,@Order
// It's a full or lite configuration candidate... Let's determine the order value, if any.
Integer order = getOrder(metadata);
if (order != null) {
beanDef.setAttribute(ORDER_ATTRIBUTE, order);
}
return true;
}
line5中:如果configCandidates集合中没有元素,那么就不操作了,因为当前这个ConfigurationClassPostProcessor最主要的作用就是解析配置类,既然容器中一个配置类都没有,那还跑个der
line6中:对configCandidates中的配置类进行排序,排序的依据是配置类上的@Order,这个可以在line4方法的解释中最底下可以看到。
line7中:创建一个Set集合,然后下面此集合就会被传入进行解析。
line8中:解析这些配置类,我们进入到这个方法里面去
public void parse(Set<BeanDefinitionHolder> configCandidates) {
this.deferredImportSelectors = new LinkedList<>();
for (BeanDefinitionHolder holder : configCandidates) {
BeanDefinition bd = holder.getBeanDefinition();
try {
// line1
if (bd instanceof AnnotatedBeanDefinition) {
parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
}
else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
}
else {
parse(bd.getBeanClassName(), holder.getBeanName());
}
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
}
}
processDeferredImportSelectors();
}
line1中:
根据不同的BeanDefinition类型,去调用不同重载的parse方法,我们以第一个AnnotatedBeanDefinition的if成立后的调用parse方法为例,进入此方法
protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
processConfigurationClass(new ConfigurationClass(metadata, beanName));
}
空壳方法,进入processConfigurationClass(new ConfigurationClass(metadata, beanName));方法中,注意此处将元数据metadata和beanName组装到ConfigurationClass去了。
protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
return;
}
ConfigurationClass existingClass = this.configurationClasses.get(configClass);
if (existingClass != null) {
if (configClass.isImported()) {
if (existingClass.isImported()) {
existingClass.mergeImportedBy(configClass);
}
// Otherwise ignore new imported config class; existing non-imported class overrides it.
return;
}
else {
// Explicit bean definition found, probably replacing an import.
// Let's remove the old one and go with the new one.
this.configurationClasses.remove(configClass);
this.knownSuperclasses.values().removeIf(configClass::equals);
}
}
// Recursively process the configuration class and its superclass hierarchy.
SourceClass sourceClass = asSourceClass(configClass);
do {
// line1
sourceClass = doProcessConfigurationClass(configClass, sourceClass);
}
while (sourceClass != null);
this.configurationClasses.put(configClass, configClass);
}
进入到line1,这才是关键代码其他地方都是校验等。
@Nullable
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
throws IOException {
// Recursively process any member (nested) classes first
processMemberClasses(configClass, sourceClass);
// Process any @PropertySource annotations
// ==============================第一部分==============================
for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), PropertySources.class,
org.springframework.context.annotation.PropertySource.class)) {
if (this.environment instanceof ConfigurableEnvironment) {
processPropertySource(propertySource);
}
else {
logger.warn("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
"]. Reason: Environment must implement ConfigurableEnvironment");
}
}
// ==============================第一部分结束==============================
// Process any @ComponentScan annotations
// ==============================第二部分==============================
Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
if (!componentScans.isEmpty() &&
!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
for (AnnotationAttributes componentScan : componentScans) {
// The config class is annotated with @ComponentScan -> perform the scan immediately
Set<BeanDefinitionHolder> scannedBeanDefinitions =
this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName()); // line1
// Check the set of scanned definitions for any further config classes and parse recursively if needed
for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
if (bdCand == null) {
bdCand = holder.getBeanDefinition();
}// line2
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
parse(bdCand.getBeanClassName(), holder.getBeanName());
}
}
}
}
// ==============================第二部分结束==============================
// Process any @Import annotations
processImports(configClass, sourceClass, getImports(sourceClass), true);
// Process any @ImportResource annotations
AnnotationAttributes importResource =
AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
if (importResource != null) {
String[] resources = importResource.getStringArray("locations");
Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
for (String resource : resources) {
String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
configClass.addImportedResource(resolvedResource, readerClass);
}
}
// Process individual @Bean methods
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}
// Process default methods on interfaces
processInterfaces(configClass, sourceClass);
// Process superclass, if any
if (sourceClass.getMetadata().hasSuperClass()) {
String superclass = sourceClass.getMetadata().getSuperClassName();
if (superclass != null && !superclass.startsWith("java") &&
!this.knownSuperclasses.containsKey(superclass)) {
this.knownSuperclasses.put(superclass, configClass);
// Superclass found, return its annotation metadata and recurse
return sourceClass.getSuperClass();
}
}
// No superclass -> processing is complete
return null;
}
第一部分:拿到PropertySource注解的内容进行解析
第二部分的line1:使用componentScanParser解析器去解析ComponentScans的包名并拿到配置包名下的所有BeanDefinition
第二部分的line2:遍历解析到的BeanDefinition,如果此BeanDefiniton是配置类,那么就递归调用parse方法再去解析此配置类的信息
后面的 就是解析Import、ImportResource,有兴趣的自己看看。
有兴趣的可以看看第二部分的line1源码,那里面对@CompentScan的每个字段都进行了获取解析,并使用this.componentScanParser的doScan方法进行实现扫描指定包的功能。
注:
本文提供大概思路,并不是对每一行代码详细解析,有错误的地方欢迎指出。