Spring5 source parsing (scan beans)

Test case code blocks

@componentScan ({"com.llsydn"}) @configuration public class AppConfig {@bean public ConfigDao1 ConfigDao1() {// return new configDao1(); } @bean public ConfigDao2 ConfigDao2 (){// write a ConfigDao2 class configDao1(); return new ConfigDao2(); }} @component public class IndexDao {public void query(){system.out.println ("query"); }} / / Test. The Java class public static void main (String [] args) {AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(); ac.register(AppConfig.class); ac.refresh(); IndexDao indexDao = ac.getBean(IndexDao.class); System.out.println(indexDao); indexDao.query(); }Copy the code
  • I am here with AnnotationConfigApplicationContext class initialization spring environment directly, this class is based on the annotation configuration application context (that is, is to use annotations to initialize a spring container)
To annotate the Bean definition in the Spring class, there are two: AnnotationConfigApplicationContext and AnnotationConfigWebApplicationContex. AnnotationConfigWebApplicationContext is AnnotationConfigApplicationContext web version The usage and handling of annotation methods almost no difference Public void register(Class<? Class) public void register(Class<? >... But there are two ways to register an annotated bean directly into the container: 1. Register it when the container is initialized and parse it; 2. You can also manually register the annotation bean by calling the registration method after the container is created, and then manually refresh the container to have the container process the registered annotation bean. 2. Scan all classes under the specified package and its subpackagesCopy the code

Next, enter the Spring container initialization source analysis

  • (1) AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext ();
Public class AnnotationConfigApplicationContext extends GenericApplicationContext / * * * this class just as its name implies is a reader, a reader what * read? Or just as its name implies AnnotatedBeanDefinition mean reading a bean * be added annotations in the method of constructing the class instantiation of * / private final AnnotatedBeanDefinitionReader reader; / * * * agree, as the name implies, it is a scanner to scan all bean * is same with annotations in the constructor is instantiated * / private final ClassPathBeanDefinitionScanner scanner; /** * initialize the reader and scanner of a bean * what is the reader and scanner refer to the property comment above * The default constructor, if called directly, needs to be registered later by calling its register() * deregister configuration class (javaconfig), And calls the refresh() method to refresh the container, * trigger the containers for annotations Bean load, parsing, and registration process * / public AnnotationConfigApplicationContext () {/ * * * * of the parent class constructor to create a Bean definition reader read notes * What is a bean definition? BeanDefinition */ this.reader = new AnnotatedBeanDefinitionReader(this); // Can be used to scan packages or classes, And then converted to bd / / but actually we scan package work is not scanner is / / the object to fulfill the spring new a ClassPathBeanDefinitionScanner / / the scanner here merely for programmers to outside call object AnnotationConfigApplicationContext scan method. This scanner = new ClassPathBeanDefinitionScanner(this); }Copy the code

Here to create a AnnotationConfigApplicationContext object, mainly to do three major operations. 1. Create a new DefaultListableBeanFactory () is a container 2 Bean factory. Create a new AnnotatedBeanDefinitionReader (this), is the reader three beans. Create a new ClassPathBeanDefinitionScanner (this), is the Bean’s scanner

Why this will create a DefaultListableBeanFactory () the beanFactory instance? The beanFactory is used to store Spring-managed Bean objects, a factory where beans are stored. Step 2. How can invoke the new DefaultListableBeanFactory ()?

Because of AnnotationConfigApplicationContext inherited GenericApplicationContext, be in namely create AnnotationConfigApplicationContext object, Will perform the superclass GenericApplicationContext constructor. So here is in the parent class constructor, execute the new DefaultListableBeanFactory () creates a the beanFactory object. public GenericApplicationContext() { this.beanFactory = new DefaultListableBeanFactory(); }

AnnotationConfigApplicationContext inherited GenericApplicationContext GenericApplicationContext BeanDefinitionRegistry is realized

  1. That is: AnnotationConfigApplicationContext also implements BeanDefinitionRegistry AnnotationConfigApplicationContext is a registry class.
  2. This registry is important, with registerBeanDefinition (registering a bean definition to a bean factory), getBeanDefinition (getting a bean definition from the bean factory), and so on. So AnnotationConfigApplicationContext is also can have the bean factory registered in the bean’s ability.
//创建一个bean读取器过程分析:
this.reader = new AnnotatedBeanDefinitionReader(this);

public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
	this(registry, getOrCreateEnvironment(registry));
}

public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
	this.registry = registry;  //将registry赋值
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
	AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}

public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
    //主要方法
	registerAnnotationConfigProcessors(registry, null);
}

public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(BeanDefinitionRegistry registry, @Nullable Object source) {
	//获取到刚创建完的DefaultListableBeanFactory对象,然后给这个对象的某些属性赋值。
	DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
	if (beanFactory != null) {
		if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
			//AnnotationAwareOrderComparator主要能解析@Order注解和@Priority
			beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
		}
		if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
			//ContextAnnotationAutowireCandidateResolver提供处理延迟加载的功能
			beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
		}
	}

	//给Spring容器添加Spring内部的特殊Bean对象(7个)
	//1.往BeanDefinitionMap注册一个ConfigurationClassPostProcessor
	Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
	//BeanDefinitio的注册,这里很重要,需要理解注册每个bean的类型
	if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
		//需要注意的是ConfigurationClassPostProcessor的类型是BeanDefinitionRegistryPostProcessor
		//而 BeanDefinitionRegistryPostProcessor 最终实现BeanFactoryPostProcessor这个接口
		RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
		def.setSource(source);
		beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
	}

	//2.往BeanDefinitionMap注册一个AutowiredAnnotationBeanPostProcessor
	if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
		//AutowiredAnnotationBeanPostProcessor 实现了 MergedBeanDefinitionPostProcessor
		//MergedBeanDefinitionPostProcessor 最终实现了 BeanPostProcessor
		RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
		def.setSource(source);
		beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
	}

	//3.往BeanDefinitionMap注册一个RequiredAnnotationBeanPostProcessor
	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));
	}

	//4.往BeanDefinitionMap注册一个CommonAnnotationBeanPostProcessor
	// 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));
	}

	//5.往BeanDefinitionMap注册一个PersistenceAnnotationBeanPostProcessor
	// 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));
	}

	//6.往BeanDefinitionMap注册一个EventListenerMethodProcessor
	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));
	}

	//7.往BeanDefinitionMap注册一个DefaultEventListenerFactory
	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;
}

//将**Processor类型的对象,注册到bean工厂中
private static BeanDefinitionHolder registerPostProcessor(BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) {
	definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
	//这里主要的代码,将bean定义注册到bean工厂当中
	registry.registerBeanDefinition(beanName, definition);
	return new BeanDefinitionHolder(definition, beanName);
}
Copy the code

Here to create a AnnotatedBeanDefinitionReader object, mainly made of two main operations: 1. Give the GenericApplicationContext () some of the qualities of the newly created object of the beanFactory assignment:

beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE); (mainly can parse @ Order annotations and @ Priority). The beanFactory setAutowireCandidateResolver (new ContextAnnotationAutowireCandidateResolver ()); (Provides the ability to handle lazy loading)

2. Register 6 spring internal objects to the bean factory, mainly objects of type **BeanPostProcessor. (One of Spring’s extension points)

Here is particularly important class ConfigurationClassPostProcessor, this class complete scan of the bean.

  • (2) ac. Register (AppConfig. Class);
/** * Register a single bean to the container * for example, if there is a new class added, you can use this method * but after registration, you need to manually call refresh to trigger the container to parse the annotation ** has two meanings: Public void register(Class<? >... annotatedClasses) { this.reader.register(annotatedClasses); } public void register(Class<? >... annotatedClasses) { for (Class<? > annotatedClass : annotatedClasses) { registerBean(annotatedClass); } } public void registerBean(Class<? > annotatedClass) {// doRegisterBean(annotatedClass, null, null, null); } <T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name, @Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... DefinitionCustomizers) {/ * * * according to the specified bean creates a AnnotatedGenericBeanDefinition * this AnnotatedGenericBeanDefinition can be understood as a data structure * AnnotatedGenericBeanDefinition contains a class of other information, such as some meta information: The scope, lazy, and so on * / AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition (annotatedClass); /** * determine whether the class needs to skip parsing. Main judge any kind comment * / if (this. ConditionEvaluator. ShouldSkip (abd) for getMetadata ())) {return; } abd.setInstanceSupplier(instanceSupplier); / * * * get class scope * / ScopeMetadata ScopeMetadata = this. ScopeMetadataResolver. ResolveScopeMetadata (abd); / * * * the class is added to the scope of the data structure of * / abd setScope (scopeMetadata. GetScopeName ()); BeanName = (name! = null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry)); /** * Common annotations in the processing class * the source code shows that he mainly handles * Lazy DependsOn Primary Role and so on * After processing is completed processCommonDefinitionAnnotations is still put him in added to the data structure of * / AnnotationConfigUtils.processCommonDefinitionAnnotations(abd); /** * If an additional Qualifier annotation is used when registering the annotation Bean definition with the container * The main thing to notice here is that the byName and qualiFIERS are an array of Annotation types, so it's not just the Qualifier annotations. So you can see the following code Spring loops through the array * and then determines whether the annotation contains Primary, Lazyd */ if (Qualifiers! = null) { for (Class<? extends Annotation> qualifier : If (Primary. Class == Primary) {abd.setprimary (true); } else if (lazy. class == qualifier) {abd.setLazyinit (true); } else {// If @primary and @lazy are used, add a qualifier for the Bean that is automatically assembled by name. Later in detail abd addQualifier (new AutowireCandidateQualifier (qualifier)); } } } for (BeanDefinitionCustomizer customizer : definitionCustomizers) { customizer.customize(abd); } /** * Make sure that beanDefinition, definitionholder, and definitionholder are not specified. Aliases []) */ definitionHolder definitionHolder = new definitionHolder (abd, beanName); /** * ScopedProxyMode Need to combine the web to understand * / definitionHolder = AnnotationConfigUtils applyScopedProxyMode (scopeMetadata definitionHolder, this.registry); / * * * the above the data structure of registration to the registy is AnnotatonConfigApplicationContext registry * * AnnotatonConfigApplicationContext when initialized by calling the superclass constructor * instantiates a DefaultListableBeanFactory * * registerBeanDefinition is definitionHolder inside the information contained in this data structure to register * * / DefaultListableBeanFactory this factory BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry); } // registerBeanDefinition with bean factory; public static void registerBeanDefinition(definitionHolder definitionHolder, BeanDefinitionRegistry registry)throws BeanDefinitionStoreException{ String beanName = definitionHolder.getBeanName(); registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); String[] aliases = definitionHolder.getAliases(); if (aliases ! = null) { for (String alias : aliases) { registry.registerAlias(beanName, alias); } } } //DefaultListableBeanFactory public void registerBeanDefinition(String beanName, BeanDefinition BeanDefinition) throws BeanDefinitionStoreException {/ / main code:  this.beanDefinitionMap.put(beanName, beanDefinition); this.beanDefinitionNames.add(beanName); this.manualSingletonNames.remove(beanName); }Copy the code

ac.register(AppConfig.class); The main purpose of the AppConfig class is to register the AppConfig class with the bean factory. So far, there are seven BeanDefinitions in the Bean factory.

  • (3) ac. Refresh (); The most important step here is to implement the scan and initialization phase of the bean
public void refresh() throws BeansException, An IllegalStateException {synchronized (enclosing startupShutdownMonitor) {/ / preparation including set start time, whether the activation identifier, // Initialize the prepareRefresh() property source; / / return a factory why need to return a factory / / for factory to initialize ConfigurableListableBeanFactory the beanFactory = obtainFreshBeanFactory (); PrepareBeanFactory (beanFactory); Try {// This method doesn't have any code in the current version of Spring // Spring might expect to extend the postProcessBeanFactory(beanFactory) in a later version; // Set to execute a custom ProcessBeanFactory and spring's own internal (important, Implementation bean scan, etc.) invokeBeanFactoryPostProcessors (the beanFactory); / / registered beanPostProcessor registerBeanPostProcessors (the beanFactory); initMessageSource(); / / initialize the application event broadcast initApplicationEventMulticaster (); // Initialize other special beans in specific context subclasses. onRefresh(); // Check for listener beans and register them. registerListeners(); / / instantiate the single object of bean (important) finishBeanFactoryInitialization (the beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { throw ex; }}}Copy the code
  • prepareRefresh
protected void prepareRefresh() { this.startupDate = System.currentTimeMillis(); this.closed.set(false); this.active.set(true); if (logger.isInfoEnabled()) { logger.info("Refreshing " + this); } // Initialize any property sources in the context environment; // Placeholder property sources should not be subclassed initPropertySources(); // Validate that all properties marked as required are resolvable // see ConfigurablePropertyResolver#setRequiredProperties getEnvironment().validateRequiredProperties(); // Allow for the collection of early ApplicationEvents, // to be published once the multicaster is available... this.earlyApplicationEvents = new LinkedHashSet<>(); }Copy the code
  • obtainFreshBeanFactory
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
	refreshBeanFactory();
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	if (logger.isDebugEnabled()) {
		logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
	}
	return beanFactory;
}

//GenericApplicationContext
@Override
public final ConfigurableListableBeanFactory getBeanFactory() {
	return this.beanFactory;
}
Copy the code
  • prepareBeanFactory
/** * configure its standard features, For example, the context's ClassLoader and post-processors callback * takes the beanFactory argument equal to DefaultListableFactory */ protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { // Tell the internal bean factory to use the context's  class loader etc. beanFactory.setBeanClassLoader(getClassLoader()); // The bean expression interpreter, Can get bean attributes on the front page of the beanFactory. SetBeanExpressionResolver (new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); / / object and type string conversion < property red = "dao" > the beanFactory. AddPropertyEditorRegistrar (new ResourceEditorRegistrar (this, getEnvironment())); / / / / add a rear manager ApplicationContextAwareProcessor can Aware in bean to various * (* Aware has its role). The beanFactory addBeanPostProcessor (new ApplicationContextAwareProcessor(this)); // Make the ApplicationContextAware interface implementation class impossible to inject dependencies of the applicationContext object during autowunning. / / (can't use the set of XML injection method or way, but you can use the @autowired injection). The beanFactory ignoreDependencyInterface (EnvironmentAware. Class); beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); beanFactory.ignoreDependencyInterface(MessageSourceAware.class); beanFactory.ignoreDependencyInterface(ApplicationContextAware.class); // BeanFactory interface not registered as resolvable type in a plain factory. // MessageSource registered (and found for autowiring) as a bean. beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this); // Register early post-processor for detecting inner beans as ApplicationListeners. beanFactory.addBeanPostProcessor(new  ApplicationListenerDetector(this)); // Detect a LoadTimeWeaver and prepare for weaving, if found. if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); // Set a temporary ClassLoader for type matching. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } // If there are no beans named "systemProperties" and "systemEnvironment" in the custom Bean, register two BenAs. // these two beans are some system configuration and systemEnvironment information if (! The beanFactory. ContainsLocalBean (ENVIRONMENT_BEAN_NAME)) {/ / directly into the beanFactory factory add bean object (the object has been new) beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } if (! beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME,  getEnvironment().getSystemProperties()); } if (! beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); } } public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException { synchronized (this.singletonObjects) { Object oldObject = this.singletonObjects.get(beanName); if (oldObject ! = null) { throw new IllegalStateException(); } addSingleton(beanName, singletonObject); Void addSingleton(String beanName, String beanName, String beanName, String beanName); Object singletonObject) { synchronized (this.singletonObjects) { this.singletonObjects.put(beanName, singletonObject); this.singletonFactories.remove(beanName); this.earlySingletonObjects.remove(beanName); this.registeredSingletons.add(beanName); }}Copy the code

The prepareBeanFactory method is used to assign values to certain properties of the beanFactory. 2. Add the beanFactory BeanPostProcessor: ApplicationContextAwareProcessor (can intervene in the bean’s initialization, extension points) was one of the three. Add an instance of system configuration and system environment information to beanFactory.

  • invokeBeanFactoryPostProcessors
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	//这个地方需要注意getBeanFactoryPostProcessors()是获取手动给spring的BeanFactoryPostProcessor
	//自定义并不仅仅是程序员自己写的
	//自己写的可以加companent也可以不加
	//如果加了getBeanFactoryPostProcessors()这个地方得不得,是spring自己扫描的
	//为什么得不到getBeanFactoryPostProcessors()这个方法是直接获取一个list,
	//这个list是在AnnotationConfigApplicationContext被定义
	//所谓的自定义的就是你手动调用AnnotationConfigApplicationContext.addBeanFactoryPostProcesor();
	PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
}

public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
	Set<String> processedBeans = new HashSet<>();
	if (beanFactory instanceof BeanDefinitionRegistry) {
		BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

		//定义了两个list存放
		List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
		List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

		//自定义的beanFactoryPostProcessors
		for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
			if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
				BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;
				registryProcessor.postProcessBeanDefinitionRegistry(registry);
				registryProcessors.add(registryProcessor);
			}else {
				regularPostProcessors.add(postProcessor);
			}
		}
		
		//这个currentRegistryProcessors 放的是spring内部自己实现了BeanDefinitionRegistryPostProcessor接口的对象
		List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

		//BeanDefinitionRegistryPostProcessor  等于 BeanFactoryPostProcessor
		//getBeanNamesForType  根据bean的类型获取bean的名字ConfigurationClassPostProcessor
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
		//这个地方可以得到一个BeanFactoryPostProcessor,因为是spring默认在最开始自己注册的
		//为什么要在最开始注册这个呢?
		//因为spring的工厂需要许解析去扫描等等功能
		//而这些功能都是需要在spring工厂初始化完成之前执行
		//要么在工厂最开始的时候、要么在工厂初始化之中,反正不能再之后
		//因为如果在之后就没有意义,因为那个时候已经需要使用工厂了
		//所以这里spring'在一开始就注册了一个BeanFactoryPostProcessor,用来插手springfactory的实例化过程
		//在这个地方断点可以知道这个类叫做ConfigurationClassPostProcessor
		//ConfigurationClassPostProcessor那么这个类能干嘛呢?可以参考源码
		//下面我们对这个牛逼哄哄的类(他能插手spring工厂的实例化过程还不牛逼吗?)重点解释
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				processedBeans.add(ppName);
			}
		}
		//排序不重要,况且currentRegistryProcessors这里也只有一个数据
		sortPostProcessors(currentRegistryProcessors, beanFactory);
		//合并list,不重要(为什么要合并,因为还有自己的)
		registryProcessors.addAll(currentRegistryProcessors);

		//最重要。注意这里是方法调用
		//执行所有BeanDefinitionRegistryPostProcessor(开始执行扫描包)
		invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);

		//执行完成了所有BeanDefinitionRegistryPostProcessor
		//这个list只是一个临时变量,故而要清除
		currentRegistryProcessors.clear();

		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.
		//执行BeanFactoryPostProcessor的回调,前面不是吗?
		//前面执行的BeanFactoryPostProcessor的子类BeanDefinitionRegistryPostProcessor的回调
		//这是执行的是BeanFactoryPostProcessor    postProcessBeanFactory
		//ConfuguratuonClassPpostProcssor
		invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
		//自定义BeanFactoryPostProcessor
		invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
	}

	else {
		// Invoke factory processors registered with the context instance.
		invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
	}

	// 这里为什么要再重复执行一遍?
	// 因为经过上面的ConfuguratuonClassPpostProcssor对bean的扫描,扫描到的bean对象有可能是实现了BeanFactoryPostProcessor接口的,所以要这这些扫描处理的bena进行再一步处理

	// Do not initialize FactoryBeans here: We need to leave all regular beans
	// uninitialized to let the bean factory post-processors apply to them!
	//ConfigurationClassPostProcessor
	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();
}

private static void invokeBeanDefinitionRegistryPostProcessors(
			Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {
	//因为只有一条数据:ConfigurationClassPostProcessor
	for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
		postProcessor.postProcessBeanDefinitionRegistry(registry);
	}
}

//ConfigurationClassPostProcessor
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
	int registryId = System.identityHashCode(registry);
	if (this.registriesPostProcessed.contains(registryId)) {
		throw new IllegalStateException();
	}
	if (this.factoriesPostProcessed.contains(registryId)) {
		throw new IllegalStateException();
	}
	this.registriesPostProcessed.add(registryId);
	//执行
	processConfigBeanDefinitions(registry);
}

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
	//定义一个list存放app 提供的bd(项目当中提供了@Compent)
	List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
	//获取容器中注册的所有bd名字
	//7个
	String[] candidateNames = registry.getBeanDefinitionNames();

	/**
	 * Full , Lite
	 */
	for (String beanName : candidateNames) {
		BeanDefinition beanDef = registry.getBeanDefinition(beanName);
		if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
				ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
			//果BeanDefinition中的configurationClass属性为full或者lite,则意味着已经处理过了,直接跳过
			//这里需要结合下面的代码才能理解
			if (logger.isDebugEnabled()) {
				logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
			}
		}
		//判断是否是Configuration类,如果加了Configuration下面的这几个注解就不再判断了
		// 还有  add(Component.class.getName());
		//		candidateIndicators.add(ComponentScan.class.getName());
		//		candidateIndicators.add(Import.class.getName());
		//		candidateIndicators.add(ImportResource.class.getName());
		//beanDef == appconfig
		else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
			//BeanDefinitionHolder 也可以看成一个数据结构
			configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
		}
	}

	// 排序,根据order,不重要
	// Sort by previously determined @Order value, if applicable
	configCandidates.sort((bd1, bd2) -> {
		int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
		int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
		return Integer.compare(i1, i2);
	});


	SingletonBeanRegistry sbr = null;
	//如果BeanDefinitionRegistry是SingletonBeanRegistry子类的话,
	// 由于我们当前传入的是DefaultListableBeanFactory,是SingletonBeanRegistry 的子类
	// 因此会将registry强转为SingletonBeanRegistry
	if (registry instanceof SingletonBeanRegistry) {
		sbr = (SingletonBeanRegistry) registry;
		if (!this.localBeanNameGeneratorSet) {
			//是否有自定义的
			BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
			//SingletonBeanRegistry中有id为 org.springframework.context.annotation.internalConfigurationBeanNameGenerator
			//如果有则利用他的,否则则是spring默认的
			if (generator != null) {
				this.componentScanBeanNameGenerator = generator;
				this.importBeanNameGenerator = generator;
			}
		}
	}
	
	//实例化ConfigurationClassParser 为了解析各个配置类
	ConfigurationClassParser parser = new ConfigurationClassParser(
			this.metadataReaderFactory, this.problemReporter, this.environment,
			this.resourceLoader, this.componentScanBeanNameGenerator, registry);

	//实例化2个set,candidates用于将之前加入的configCandidates进行去重
	//因为可能有多个配置类重复了
	//alreadyParsed用于判断是否处理过
	Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
	Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
	do {
		//很重要(扫描bean)
		parser.parse(candidates);
		parser.validate();
		//map.keyset
		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());
		}

		/**
		 * 这里值得注意的是扫描出来的bean当中可能包含了特殊类
		 * 比如ImportBeanDefinitionRegistrar那么也在这个方法里面处理
		 * 但是并不是包含在configClasses当中
		 * configClasses当中主要包含的是importSelector
		 * 因为ImportBeanDefinitionRegistrar在扫描出来的时候已经被添加到一个list当中去了
		 */
		//bd 到 map 除却普通 (将import的bean注册到bean工厂)(重要)
		this.reader.loadBeanDefinitions(configClasses);
		alreadyParsed.addAll(configClasses);

		candidates.clear();
		//由于我们这里进行了扫描,把扫描出来的BeanDefinition注册给了factory
		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;
		}
	}
}

//ConfigurationClassParser
public void parse(Set<BeanDefinitionHolder> configCandidates) {
	this.deferredImportSelectors = new LinkedList<>();
	//根据BeanDefinition 的类型 做不同的处理,一般都会调用ConfigurationClassParser#parse 进行解析
	for (BeanDefinitionHolder holder : configCandidates) {
		BeanDefinition bd = holder.getBeanDefinition();
		try {
			if (bd instanceof AnnotatedBeanDefinition) {
				//解析注解对象,并且把解析出来的bd放到map,但是这里的bd指的是普通的
				//何谓不普通的呢?比如@Bean 和各种beanFactoryPostProcessor得到的bean不在这里put
				//但是是这里解析,只是不put而已
				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());
			}
		}
	}
	//处理延迟加载的importSelect?为什么要延迟加载,估计就是为了延迟吧
	processDeferredImportSelectors();
}

protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
	processConfigurationClass(new ConfigurationClass(metadata, beanName));
}

protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
	if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
		return;
	}
	// 处理Imported 的情况
	// 就是当前这个注解类有没有被别的类import
	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 imports.
			// 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 {
		//具体的实现(重要)
		sourceClass = doProcessConfigurationClass(configClass, sourceClass);
	}
	while (sourceClass != null);
	//一个map,用来存放扫描出来的bean(注意这里的bean不是对象,仅仅bean的信息,因为还没到实例化这一步)
	this.configurationClasses.put(configClass, configClass);
}

protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
			throws IOException {
	// 处理内部类
	processMemberClasses(configClass, sourceClass);

	// 处理@PropertySource注解
	for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
			sourceClass.getMetadata(), PropertySources.class,
			org.springframework.context.annotation.PropertySource.class)) {
		if (this.environment instanceof ConfigurableEnvironment) {
			processPropertySource(propertySource);
		}
	}
	
	// 处理@ComponentScan注解
	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) {
			//扫描普通类=componentScan=com.llsydn
			//这里扫描出来所有@Component
			//并且把扫描的出来的普通bean放到map当中
			Set<BeanDefinitionHolder> scannedBeanDefinitions =
					this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
			
			//检查扫描出来的类当中是否还有configuration
			for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
				BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
				if (bdCand == null) {
					bdCand = holder.getBeanDefinition();
				}
				//检查到有的,再执行一次parse方法
				if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
					parse(bdCand.getBeanClassName(), holder.getBeanName());
				}
			}
		}
	}

	/**
	 * 上面的代码就是扫描普通类----@Component
	 * 并且放到了map当中
	 */
	// Process any @Import annotations
	//处理@Import  imports 3种情况
	//ImportSelector
	//普通类
	//ImportBeanDefinitionRegistrar
	//这里和内部地柜调用时候的情况不同
	/**
	 * 这里处理的import是需要判断我们的类当中时候有@Import注解
	 * 如果有这把@Import当中的值拿出来,是一个类
	 * 比如@Import(xxxxx.class),那么这里便把xxxxx传进去进行解析
	 * 在解析的过程中如果发觉是一个importSelector那么就回调selector的方法
	 * 返回一个字符串(类名),通过这个字符串得到一个类
	 * 继而在递归调用本方法来处理这个类
	 *
	 * 判断一组类是不是imports(3种import)
	 */
	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);
		}
	}

	// 处理@Bean方法
	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;
}

//ComponentScanAnnotationParser,扫描普通的@component
public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
			componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);
	//扫描包(重点)
	return scanner.doScan(StringUtils.toStringArray(basePackages));
}

//ClassPathBeanDefinitionScanner
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
	Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
	for (String basePackage : basePackages) {
		//扫描basePackage路径下的java文件
		//符合条件的并把它转成BeanDefinition类型
		Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
		for (BeanDefinition candidate : candidates) {
			//解析scope属性
			ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
			candidate.setScope(scopeMetadata.getScopeName());
			String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
			if (candidate instanceof AbstractBeanDefinition) {
				//如果这个类是AbstractBeanDefinition的子类
				//则为他设置默认值,比如lazy,init destory
				postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
			}
			if (candidate instanceof AnnotatedBeanDefinition) {
				//检查并且处理常用的注解
				//这里的处理主要是指把常用注解的值设置到AnnotatedBeanDefinition当中
				//当前前提是这个类必须是AnnotatedBeanDefinition类型的,说白了就是加了注解的类
				AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
			}
			if (checkCandidate(beanName, candidate)) {
				BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
				definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
				beanDefinitions.add(definitionHolder);
				//将bean定义注册到bean工厂中
				registerBeanDefinition(definitionHolder, this.registry);
			}
		}
	}
	return beanDefinitions;
}

//扫描包,将class转成beanDefinition
public Set<BeanDefinition> findCandidateComponents(String basePackage) {
	if (this.componentsIndex != null && indexSupportsIncludeFilters()) {
		return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);
	}
	else {
		return scanCandidateComponents(basePackage);
	}
}

//利用asm技术读取class文件,并将class文件转成beanDefinition
private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
	Set<BeanDefinition> candidates = new LinkedHashSet<>();
	try {
		String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
				resolveBasePackage(basePackage) + '/' + this.resourcePattern;
		//asm 读取class文件
		Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
		boolean traceEnabled = logger.isTraceEnabled();
		boolean debugEnabled = logger.isDebugEnabled();
		for (Resource resource : resources) {
			if (resource.isReadable()) {
				try {
					MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
					if (isCandidateComponent(metadataReader)) {
						ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
						sbd.setResource(resource);
						sbd.setSource(resource);
						if (isCandidateComponent(sbd)) {
							candidates.add(sbd);
						}
					}
				}
			}
		}
	}
	return candidates;
}



Copy the code

InvokeBeanFactoryPostProcessors main function: 1. Execute spring’s internal **BeanFactoryPostProcessor method. (ConfigurationClassPostProcessor)

ConfigurationClassPostProcessor main role is to implement the bean’s scanning, and implement beanDefinition registered to bean in the factory

One of the extension points of BeanFactoryPostProcessor Spring: 1. Implementing this interface allows you to modify the definition properties of spring beans before they are created. Spring allows BeanFactoryPostProcessor to read the configuration metadata before the container instantiates any other beans. You can change the scope of the bean from Singleton to Prototype, or change the value of the property. 4. Multiple BeanFactoryPostProcessors can be configured at the same time and the order of execution of each BeanFactoryPostProcessor can be controlled by setting the ‘order’ property. 5. Spring BeanFactoryPostProcessor is after the spring container loading the bean definition file, perform before bean instantiation.

BeanDefinitionRegistryPostProcessor spring BeanFactoryPostProcessor is realized. Is, on the propagation of the spring BeanFactoryPostProcessor postProcessBeanDefinitionRegistry method has been added, can the Bean plant, registered a BeanDefinition object.

Copy the code