1. 起点
public class AopDemo {
static public void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
context.getBean(MathCalculator.class).div(4, 2);
}
}
2. 新建,初始化容器
AnnotationConfigApplicationContext 层级
public AnnotationConfigApplicationContext(Class>... annotatedClasses) {
this();
register(annotatedClasses);
refresh();
}
- this(): 创建容器,并初始化beanMap
- 创建BeanFactory
AnnotationConfigApplicationContext 继承 GenericApplicationContext,在调用AnnotationConfigApplicationContext的构造函数时,会先调用父类的构造函数创建BeanFactory:
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
org.springframework.context.annotation.internalConfigurationAnnotationProcessor,
org.springframework.context.annotation.internalAutowiredAnnotationProcessor,
org.springframework.context.annotation.internalRequiredAnnotationProcessor,
org.springframework.context.annotation.internalCommonAnnotationProcessor,
org.springframework.context.annotation.internalPersistenceAnnotationProcessor,
org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor,
org.springframework.context.event.internalEventListenerProcessor,
org.springframework.context.event.internalEventListenerFactory
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
- 初始化自定义类:就是例子中的MainConfig
- register(annotatedClasses);
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
- refresh 刷新容器:实例化bean,创建Bean代理都是在这一步