spring bean 수명 주기 3 (spring 5.0 버 전)
45409 단어 스프링 소스 코드
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
this();
register(componentClasses);
refresh();
}
본 고 는 위 와 같은 refresh () 방법 invokeBeanFactory PostProcessors (beanFactory)
refresh () 방법 추적: invokeBeanFactory PostProcessors (beanFactory) 이 방법 이전의 주석 은 모두 방법 에 적 혀 있 습 니 다.
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// ,
prepareRefresh();
// beanfactory beanfactory, bdmap 6 bdmap
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// , BeanPostProcessor ApplicationContextAwareProcessor
prepareBeanFactory(beanFactory);
try {
// ,spring
postProcessBeanFactory(beanFactory);
//
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
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();
}
}
}
invokeBeanFactory PostProcessors (beanFactory) 방법 추적:
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// loadTimeWeaver bean, Aspectj
// AspectJ 、
// LTW(Load Time Weaving), JVM
// , AspectJ ;
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
추적 PostProcessor Registration Delegate. invokeBeanFactory PostProcessors (beanFactory, getBeanFactory PostProcessors ());주석 이 방법 에 쓰 여 있다.
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// beanname.
Set<String> processedBeans = new HashSet<>();
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// bean , bfpp,
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
// bean , bdrpp,
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
// beanFactoryPostProcessors ,
// applicationContext beanFactoryPostProcessors
// , refresh()
// :
//AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
//ac.register(Appconfig.class);
//ac.addBeanFactoryPostProcessor(new MyBeanFactoryBd());
//ac.refresh();
// MyBeanFactoryBd beanFactoryPostProcessor
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
// BeanDefinitionRegistryPostProcessor bd
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// beandeinition BeanDefinitionRegistryPostProcessor ( beanname , );
// bd merge, bd parentName ( )
// : map( map factorybean beanname) parentname & , map , ,
map , , parentname
beanname, parentname bd
, bd RootBeanDefinition, mergeMap ,
bd, , , mergemap ;
// : bd RootBeanDefinition, mergeMap ,
// bd RootBeanDefinition
// bd , , factorbean , beanname & , bd
//BeanDefinitionRegistryPostProcessor
// name bd ConfigurationClassPostProcessor bd ;
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// bd PriorityOrdered
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// bean ,
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
//
sortPostProcessors(currentRegistryProcessors, beanFactory);
// configurationclassPostprocess registryProcessors
registryProcessors.addAll(currentRegistryProcessors);
// , configurationclassPostprocessor
// postProcessBeanDefinitionRegistry , bd beandefinition;
// :
//1, spring bd ( 6 , appconfig )
//2, appconfig :componetsacn,componet,import,importsource, , set
// beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
// spring , configurationClass lite ;
//3, componetsacn ClassPathBeanDefinitionScanner doscan() ,
// beandefinition, :
//3.1, componetsacn , spring
//3.2 spring asm metadata
//3.3 includeFilters :spring component, managebean
//( spring , spring )
// excludeFilters appconfig , , beandefinition
//ClassPathScanningCandidateComponentProvider
//private final List includeFilters = new LinkedList<>();
//private final List excludeFilters = new LinkedList<>();
// ScannedGenericBeanDefinition bd, metadata
//3.4 bd , ; ,
// Primary,Role,DependsOn , spring beandefinition map
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
//
currentRegistryProcessors.clear();
// BeanDefinitionRegistryPostProcessor ,
// ? ,
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// BeanDefinitionRegistryPostProcessor
// (configurationclassPostprocess), orderd
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
registryProcessors.addAll(currentRegistryProcessors);
// orderd BeanDefinitionRegistryPostProcessor
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
boolean reiterate = true;
// BeanDefinitionRegistryPostProcessor orderd , beanfactory , ?
// beanfactory BeanDefinitionRegistryPostProcessor ;
// ,
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();
}
// BeanFactoryPostProcessor postProcessBeanFactory
// registryProcessors
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
// ac.refresh beanfactory BeanFactoryPostProcessor
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
//
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// BeanFactoryPostProcessor ( BeanDefinitionRegistryPostProcessor )
// bd
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// priorityOrdered BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
// Ordered BeanFactoryPostProcessor
List<String> orderedPostProcessorNames = new ArrayList<>();
// BeanFactoryPostProcessor
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
// bd
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<>(orderedPostProcessorNames.size());
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<>(nonOrderedPostProcessorNames.size());
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();
}
총 결 실행 순서:
1. Bean Definition Registry PostProcessor 를 실행 하 는 하위 클래스 는 Priority Ordered 인 터 페 이 스 를 실현 합 니 다. 첫 번 째 는 spring 자신의 configurationclassPostprocess 입 니 다.이 종 류 는 우리 가 개발 한 모든 것 을 bd 대상 으로 전환시킨다.2. Bean Definition Registry PostProcessor 의 하위 클래스 를 실행 하여 ordered 인터페이스의 하위 클래스 를 실현 합 니 다.3. BeanDefinition Registry PostProcessor 의 하위 클래스 를 실행 합 니 다.4. BeanDefinition Registry PostProcessor 의 하위 클래스 를 수행 하 는 BeanFactory PostProcessor 의 post ProcessBeanFactory 방법;5. ac. refresh () 이전에 beanfactory 공장 에 가입 한 BeanFactory PostProcessor 서브 클래스 의 post ProcessBeanFactory 방법 을 집행 합 니 다.
6. BeanFactory PostProcessor 서브 클래스 를 실행 하여 Priority Ordered 인터페이스의 서브 클래스 의 post ProcessBeanFactory 방법 을 실현 합 니 다.7. BeanFactory PostProcessor 서브 클래스 를 실행 하여 Ordered 인터페이스의 서브 클래스 의 post ProcessBeanFactory 방법 을 실현 합 니 다.8. BeanFactory PostProcessor 서브 클래스 실현 류 의 post ProcessBeanFactory 방법 을 집행 합 니 다.실행 순 서 는 위 에서 아래로 실행 되면 실행 되 지 않 습 니 다.