Spring 소스 코드 의 자동 조립 을 깊이 이해 하 다.
6308 단어 스프링 소스 코드
예 를 들 어 applicationContextAware 의 전체 초기 화 과정 을 보십시오.
public class IOCTest_Autowired {
@Test
public void test01(){
AnnotationConfigApplicationContext applicationContext = new
AnnotationConfigApplicationContext(MainConifgOfAutowired.class);
}
}
package com.atguigu.bean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringValueResolver;
@Component
public class AwareBean implements ApplicationContextAware,BeanNameAware,EmbeddedValueResolverAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// TODO Auto-generated method stub
System.out.println(" ioc:"+applicationContext);
this.applicationContext = applicationContext;
}
@Override
public void setBeanName(String name) {
// TODO Auto-generated method stub
System.out.println(" bean :"+name);
}
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
// TODO Auto-generated method stub
String resolveStringValue = resolver.resolveStringValue(" ${os.name} #{20*18}");
System.out.println(" :"+resolveStringValue);
}
}
정지점 호출 스 택 보기:
-->AnnotationConfigApplicationContext refresh();
-->finishBeanFactoryInitialization(beanFactory);
-->beanFactory.preInstantiateSingletons()
-->DefaultListableBeanFactory getBean(beanName)
-->AbstractBeanFactory doGetBean(name, null, null, false);
-->AbstractBeanFactory getSingleton(beanName, new ObjectFactory
applicationContextAware Processor 의 원본 코드 를 열 어 보 니 BeanPostProcessor 사전 클래스 가 post ProcessBeforeInitialization 방법 에서 invoke Aware Interfaces 를 마지막 단계 로 호출 할 때 spring 용 기 를 설정 합 니 다.
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof Aware) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
}