spring注解启动类AnnotationConfigApplicationContext
spring容器是由很多个Map和其他属性组成的
// 通过传入DemoApplication配置类(这个类作用相当于xml配置文件)来启动spring容器
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(DemoApplication.class);
创建AnnotationConfigApplicationContext实例会调用下面3个方法
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
1.创建ioc容器
this();
2.将配置类(DemoApplication类)的定义信息加载到容器中
register(annotatedClasses);
3.刷新容器
refresh();
}
this()方法就是调用自己的无参构造函数,创建上下文容器AnnotationConfigApplicationContext,创建一个this.beanFactory = new DefaultListableBeanFactory();
因为AnnotationConfigApplicationContext继承了GenericApplicationContext,所以会先调用父类GenericApplicationContext的无参构造函数,创建一个DefaultListableBeanFactory的默认工厂实现类(是ConfigurableListableBeanFactory和BeanDefinitionRegistry的默认实现)
然后再调用自己的无构构造函数,初始化基于配置类的方式(new AnnotationConfigApplicationContext(配置类))和扫包方式(new AnnotationConfigApplicationContext("范围"))处理spring的启动
register(annotatedClasses)方法,将配置类(DemoApplication类)的定义信息加载到容器中(并未作创建DemoApplication类的bean实例的操作),只是将类的定义信息保存
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
// 加载配置类的定义信息
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
// condition条件的判断
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
// 设置回调方法
abd.setInstanceSupplier(instanceSupplier);
// 获取配置类scope作用域(类上没有设置scope默认设置为为单例)
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
// 将配置类的scope加载到bean的定义信息中
abd.setScope(scopeMetadata.getScopeName());
// 设置beanName(id),默认为类名首字母小字
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
// 判断配置类上是否有@Lazy、@DependsOn、@Role、@Description注解,有就加载到bean定义信息中
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));
}
}
}
// 如果有BeanDefinition的定制器(自定义一些配置),就把AnnotatedGenericBeanDefinition注入进去作定制处理
for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
customizer.customize(abd);
}
// 包装abd,将beanName注入到包装类BeanDefinitionHolder中
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
// 如果需要创建代理对象(相同作用域),就创建并返回代理对象
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
// 将配置类的定义信息加载到beanFactory中
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
refresh()方法,刷新容器(调用了12个方法处理),
主要代码方法中文注释标注
1、prepareRefresh() 刷新容器(上下文)的预处理,主要执行了
1.initPropertySources() 初始化一些属性设置;这个方法是空的,给子类自定义属性设置
2.getEnvironment() 检验属性的合法性
3.this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners); 保存容器中一些预处理时(早期)的事件;
protected void prepareRefresh() {
// Switch to active.
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
// 初始化一些属性设置;这个方法是空的,给子类自定义属性设置;
initPropertySources();
// 检验属性的合法性
getEnvironment().validateRequiredProperties();
// 保存容器中预处理的一些事件...
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}
2、obtainFreshBeanFactory();调用GenericApplicationContext的方法给beanFactory设置id,然后获取返回的BeanFactory【DefaultListableBeanFactory】对象
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 给beanFactory设置id
refreshBeanFactory();
// 获取DefaultListableBeanFactory
return getBeanFactory();
}
3、prepareBeanFactory(beanFactory) BeanFactory的预准备工作(对BeanFactory进行一些设置)
1.设置BeanFactory的类加载器、表达式解析器、属性编辑器
2.添加ApplicationContextAwareProcessor【BeanPostProcessor后置处理器】
3.忽略一些的自动装配的Aware接口
4.注册可以自动装配的组件;我们能直接在任何组件中自动注入BeanFactory、ResourceLoader
5.添加ApplicationListenerDetector【BeanPostProcessor后置处理器】
6.添加LoadTimeWeaverAwareProcessor(开启AspectJ的时候会调用)
7.给BeanFactory中注册一些系统组件(environment、systemEnvironment等)
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 1.设置BeanFactory的类加载器、表达式解析器、属性编辑器
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// 2.添加ApplicationContextAwareProcessor【BeanPostProcessor后置处理器】
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
// 3.忽略一些的自动装配的Aware接口
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// 4..注册可以自动装配的组件;我们能直接在任何组件中自动注入BeanFactory、ResourceLoader等
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// 5.添加ApplicationListenerDetector【BeanPostProcessor后置处理器】
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// 6.添加LoadTimeWeaverAwareProcessor(开启AspectJ的时候会调用)
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()));
}
// 7.给BeanFactory中注册一些系统组件
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
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());
}
}
4、postProcessBeanFactory(beanFactory) 由子类去重写方法,BeanFactory创建和预准备工作完成后给子类进行后置处理工作
5、invokeBeanFactoryPostProcessors(beanFactory)
执行BeanFactoryPostProcessorBeanFactory的后置处理器(在BeanFactory标准初始化之后执行的,即所有的baen定义信息已经加载到beanFactory,但是bean的实例还未创建时调用)
这一步会保存所有的bean的定义信息(被spring扫描到的bean)
这个方法处理了两个接口:BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor(这个是BeanFactoryPostProcessor的子接口)。
先处理BeanDefinitionRegistryPostProcessor的实现
1.获取所有的BeanDefinitionRegistryPostProcessor 2.先执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); 下同 3.再执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor 4.最后执行没有实现任何优先级或者是顺序接口的BeanDefinitionRegistryPostProcessors
再执行BeanFactoryPostProcessor的实现
1.获取所有的BeanFactoryPostProcessor 1.先执行实现了PriorityOrdered优先级接口的BeanFactoryPostProcessor、 invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);下同 2.再执行实现了Ordered顺序接口的BeanFactoryPostProcessor 3.最后执行没有实现任何优先级或者是顺序接口的BeanFactoryPostProcessor
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<>();
// 将BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor分别存放在两个list中
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// 先执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor、
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);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// 执行
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
//再执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor.
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();
// 最后执行没有实现任何优先级或者是顺序接口的BeanDefinitionRegistryPostProcessors;
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();
}
// 执行
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// 处理BeanFactoryPostProcessor的方法
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// 先执行实现了PriorityOrdered优先级接口的
// 在执行实现了Ordered顺序接口的, 最后执行没有实现任何优先级或者是顺序接口的
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.
// 首先处理实现了PriorityOrdered优先级接口的BeanFactoryPostProcessors
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
// 然后处理实现了Ordered顺序接口的BeanFactoryPostProcessors
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.
//最后执行没有实现任何优先级或者是顺序接口的BeanFactoryPostProcessor
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();
}
6、registerBeanPostProcessors(beanFactory) 注册BeanPostProcessor(Bean的后置处理器)
1.将实现了PriorityOrdered、Ordered和常规的BeanPostProcessor保存到不同list,然后分别注册到BeanFactory中(添加到容器的beanPostProcessors(Map集合)中) registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); 2.注册MergedBeanDefinitionPostProcessor(内部的后置处理器) 3.注册一个ApplicationListenerDetector 作用:在Bean创建完成之后,会执行这个类的postProcessAfterInitialization方法 检查这个bean是否实现了ApplicationListener,如果是就加入到事件容器中(applicationContext.addApplicationListener))
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// 将实现了PriorityOrdered、Ordered和常规的BeanPostProcessor分开保存进行处理
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, register the BeanPostProcessors that implement PriorityOrdered.
// 首先,注册实现了PriorityOrdered接口的BeanPostProcessor
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
// 首先,注册实现了Ordered接口的BeanPostProcessor
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// Now, register all regular BeanPostProcessors.
// 最后注册常规的(没有实现任何优先级接口的)BeanPostProcessor
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// Finally, re-register all internal BeanPostProcessors.
// 最后,注册MergedBeanDefinitionPostProcessor(内部的后置处理器)
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// 注册一个ApplicationListenerDetector
//(作用:在Bean创建完成之后,会执行这个类的postProcessAfterInitialization方法
//检查这个bean是否实现了ApplicationListener,如果是就加入到事件容器中(applicationContext.addApplicationListener))
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
7、initMessageSource() 初始化MessageSource组件(用于国际化功能、消息绑定、消息解析)
1.查看容器中是否有id为MESSAGE_SOURCE_BEAN_NAME、类型是MessageSource的组件,有就给MessageSource赋值 没有就创建DelegatingMessageSource并注册到IOC容器中
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 容器中是否有id为MESSAGE_SOURCE_BEAN_NAME的定义信息
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
// 获取MESSAGE_SOURCE_BEAN_NAME的bean实例(容器中没有保存就创建)
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (logger.isTraceEnabled()) {
logger.trace("Using MessageSource [" + this.messageSource + "]");
}
}
// 如果没有messageSource就创建DelegatingMessageSource并注册到ioc容器中
else {
// Use empty MessageSource to be able to accept getMessage calls.
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isTraceEnabled()) {
logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
}
}
}
8、initApplicationEventMulticaster() 初始化事件派发器(可用于发布事件)。即创建applicationEventMulticaster的实例并注册到容器中
1.从BeanFactory中获取applicationEventMulticaster的ApplicationEventMulticaster 2.如果获取不到,就创建一个SimpleApplicationEventMulticaster添加到BeanFactory中, 以后其他组件需要时可直接自动注入SimpleApplicationEventMulticaster实例
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}
9、onRefresh() 这个方法是空的,子类可以重写这个方法,在容器刷新的时候可以自定义处理逻辑
10、registerListeners() 将ApplicationListener监听器添加到派发器中
1.从BeanFactory中获取applicationEventMulticaster的ApplicationEventMulticaster 2.发布早期(之前步骤产生)的事件
// 从容器中拿到所有的ApplicationListener并将每个监听器添加到事件派发器中
protected void registerListeners() {
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 从容器中拿到所有的ApplicationListener并将每个监听器添加到事件派发器中
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// 发布早期(之前步骤产生)的事件
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
11、finishBeanFactoryInitialization(beanFactory) 实例化所有剩下的单实例bean
主要是执行beanFactory.preInstantiateSingletons()初始化后剩下的单实例bean 1.获取容器中所有beanNames,遍历所有beanNames进行创建对象和初始化,并将创建的Bean添加到缓存到IOC容器中 2.所有Bean都利用getBean创建完成以后,检查所有的Bean是否实现了SmartInitializingSingleton接口的 如果是就执行afterSingletonsInstantiated()
// 初始化后剩下的单实例bean
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// 获取容器中所有beanNames
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// 遍历所有beanNames进行创建对象和初始化
for (String beanName : beanNames) {
// 获取Bean的定义信息:RootBeanDefinition
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// 不是抽象的,是单实例的,不是懒加载的Bean 才处理
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
// 判断是否是实现了FactoryBean接口的bean
if (isFactoryBean(beanName)) {
// 如果是实现了FactoryBean接口的bean,判断是否需要马上创建,
//如果需要就调用getBean()创建,如果不需要就先不创建
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
final FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
}
// 不是工厂Bean对象(FactoryBean)。调用getBean(beanName)方法创建对象
else {
getBean(beanName);
}
}
}
// 为所有适用的bean触发初始化后回调
//检查所有的Bean是否实现了SmartInitializingSingleton接口的
//如果是就执行afterSingletonsInstantiated();
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
12、finishRefresh() 实例化所有剩下的单实例bean
1.初始化和ApplicationContext(容器,BeanFactory的实现)生命周期有关的后置处理器(LifecycleProcessor) 2.拿到上面定义的LifecycleProcessor执行回调方法onRefresh() 3.发布容器刷新完成的事件
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches();
// 初始化和ApplicationContext(容器,BeanFactory的实现)生命周期有关的后置处理器(LifecycleProcessor)
// 可自定义实现LifecycleProcessor接口重写void onRefresh()和void onClose()
initLifecycleProcessor();
// 拿到LifecycleProcessor执行回调方法onRefresh()
getLifecycleProcessor().onRefresh();
// 发布容器刷新完成的事件
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}
refresh()方法,刷新容器(调用了12个方法处理),
主要代码方法中文注释标注
1、prepareRefresh() 刷新容器(上下文)的预处理,主要执行了
1.initPropertySources() 初始化一些属性设置;这个方法是空的,给子类自定义属性设置
2.getEnvironment() 检验属性的合法性
3.this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners); 保存容器中一些预处理时(早期)的事件;2、obtainFreshBeanFactory();调用GenericApplicationContext的方法给beanFactory设置id,然后获取返回的BeanFactory【DefaultListableBeanFactory】对象
3、prepareBeanFactory(beanFactory) BeanFactory的预准备工作(对BeanFactory进行一些设置)
1.设置BeanFactory的类加载器、表达式解析器、属性编辑器
2.添加ApplicationContextAwareProcessor【BeanPostProcessor后置处理器】
3.忽略一些的自动装配的Aware接口
4.注册可以自动装配的组件;我们能直接在任何组件中自动注入BeanFactory、ResourceLoader
5.添加ApplicationListenerDetector【BeanPostProcessor后置处理器】
6.添加LoadTimeWeaverAwareProcessor(开启AspectJ的时候会调用)
7.给BeanFactory中注册一些系统组件(environment、systemEnvironment等)4、postProcessBeanFactory(beanFactory) 由子类去重写方法,BeanFactory创建和预准备工作完成后给子类进行后置处理工作
5、invokeBeanFactoryPostProcessors(beanFactory)
执行BeanFactoryPostProcessorBeanFactory的后置处理器(在BeanFactory标准初始化之后执行的,即所有的baen定义信息已经加载到beanFactory,但是bean的实例还未创建时调用)
这一步会保存所有的bean的定义信息(被spring扫描到的bean)
这个方法处理了两个接口:BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor(这个是BeanFactoryPostProcessor的子接口)。先处理BeanDefinitionRegistryPostProcessor的实现
1.获取所有的BeanDefinitionRegistryPostProcessor 2.先执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); 下同 3.再执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor 4.最后执行没有实现任何优先级或者是顺序接口的BeanDefinitionRegistryPostProcessors
再执行BeanFactoryPostProcessor的实现
1.获取所有的BeanFactoryPostProcessor 2.先执行实现了PriorityOrdered优先级接口的BeanFactoryPostProcessor、 invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);下同 3.再执行实现了Ordered顺序接口的BeanFactoryPostProcessor 4.最后执行没有实现任何优先级或者是顺序接口的BeanFactoryPostProcessor
6、registerBeanPostProcessors(beanFactory) 注册BeanPostProcessor(Bean的后置处理器)
1.将实现了PriorityOrdered、Ordered和常规的BeanPostProcessor保存到不同list,然后分别注册到BeanFactory中(添加到容器中) registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); 2.注册MergedBeanDefinitionPostProcessor(内部的后置处理器) 3.注册一个ApplicationListenerDetector 作用:在Bean创建完成之后,会执行这个类的postProcessAfterInitialization方法 检查这个bean是否实现了ApplicationListener,如果是就加入到事件容器中(applicationContext.addApplicationListener))
7、initMessageSource() 初始化MessageSource组件(用于国际化功能、消息绑定、消息解析)
1.查看容器中是否有id为MESSAGE_SOURCE_BEAN_NAME、类型是MessageSource的组件,有就给MessageSource赋值 2.没有就创建DelegatingMessageSource并注册到IOC容器中
8、initApplicationEventMulticaster() 初始化事件派发器(可用于发布事件)。即创建applicationEventMulticaster的实例并注册到容器中
1.从BeanFactory中获取applicationEventMulticaster的ApplicationEventMulticaster 2.如果获取不到,就创建一个SimpleApplicationEventMulticaster添加到BeanFactory中, 以后其他组件需要时可直接自动注入SimpleApplicationEventMulticaster实例
9、onRefresh() 这个方法是空的,子类可以重写这个方法,在容器刷新的时候可以自定义处理逻辑
10、registerListeners() 将ApplicationListener监听器添加到派发器中
1.从BeanFactory中获取applicationEventMulticaster的ApplicationEventMulticaster 2.发布早期(之前步骤产生)的事件
11、finishBeanFactoryInitialization(beanFactory) 实例化所有剩下的单实例bean,并保存到容器中
主要是执行beanFactory.preInstantiateSingletons()初始化后剩下的单实例bean 1.获取容器中所有beanNames,遍历筛选bean定义信息为单实例的beanNames进行创建对象和初始化,并将创建的Bean添加到缓存到IOC容器中 (缓存到singletonObjects(map中) ioc容器有很多的map) 2.所有单实例Bean都利用getBean创建完成以后,检查所有的Bean是否实现了SmartInitializingSingleton接口的 如果是就执行afterSingletonsInstantiated()
12、finishRefresh() 实例化所有剩下的单实例bean
1.初始化和ApplicationContext(容器,BeanFactory的实现)生命周期有关的后置处理器(LifecycleProcessor) 2.拿到上面定义的LifecycleProcessor执行回调方法onRefresh() 3.发布容器刷新完成的事件
思考问题
1.bean对象是什么时候被创建的? (spring加载时还是调用时)
单实例Bean(默认)是spring容器启动时创建的。
多实例Bean是调用的时候才创建的
如何证明?通过调用无参构造方法来证明,因为创建对象时会调用无参构造方法2.BeanFactory与FactoryBean的区别
BeanFactory(接口)是一个工厂,也就是
IOC容器
或对象工厂,负责创建和管理Bean对象的工厂,是spring用来管理和装配普通bean的ioc容器。它的职责包括:实例化、定位、配置应用程序中的对象及建立这些对象间的依赖。BeanFactory只是个接口,并不是IOC容器的具体实现,但是Spring容器给出了很多种实现,如 DefaultListableBeanFactory、XmlBeanFactory、ApplicationContext等
FactoryBean(接口)是一个bean,在IOC容器的基础上给Bean的实现加上了一个简单工厂模式和装饰模式,这个Bean不是简单的Bean,是一个可以生产对象和装饰对象的工厂bean,由spring管理后,生产的对象是由getObject()方法决定的。例如:
实现FactoryBean接口的FactoryBeanTest类生成的类,通过applicationContext.getBean("FactoryBeanTest"),获取到的类型是User,也就是
User user = (User)applicationContext.getBean("FactoryBeanTest");
BeanFactory和ApplicationContext的区别
BeanFactory:是Spring里面最低层的接口,提供了最简单的容器的功能,只提供了实例化对象和拿对象的>功能;
ApplicationContext:
应用上下文,继承BeanFactory接口
,不仅有BeanFactory所有的功能,它是Spring的一各更高级的容器,还提供了更多的有用的功能
1) 国际化(MessageSource)
2) 访问资源,如URL和文件(ResourceLoader)
3) 启动上下文容器
4) 消息发送、响应机制(ApplicationEventPublisher)
5) AOP(拦截器)
3.spring用于注入对象到IOC容器的注册有?
@Configuration+@bean、@Import、
@Component及其派生注解(@Service,@Repository等)+扫包
spring启动方式
spring xml 配置文件启动方式:
new ClassPathXmlApplicationContext("applicationContext.xml");
spring注册方式启动
new AnnotationConfigApplicationContext(MyConfiguration.class);
(MyConfiguration类上有@Configuration,@ComponentScan等注解,类似springboot)
spring的一些注解
@Configuration+@bean注解可以实现xml配置的注入,称为注解版的注入,一般用于对第三方外部jar包的类的bean的创建
(因为这些类上没有加@Service @Controller @Component等注解,不能被srping自动扫描并加载到容器中)
// @Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件
// 将user注入到springioc容器中 baen的名称id为方法名user
@Configuration
public class MyConfiguration{
// 将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
@Bean
public User user(){
return new User();
}
}
@Import作用与@bean类似,主要用于将外部jar包的类注入到springIoc容器中
在MyConfiguration类上@Import(User.class)将user注入到springioc容器中
@Configuration
@Import(User.class)
public class MyConfiguration{
/** @Bean
public User user(){
return new User();
}
**/
}
@Import注解与@Bean注解区别
bean注解注册的bean的id是以方法名称,@Import是以当前类完整路径名称注册
spring
一.bean名称(id)重复,启动时会报错
二.spring的bean默认是单例的