1.3 IOC启动流程分析
1.3.1 启动入口
org.springframework.context.support.FileSystemXmlApplicationContext#FileSystemXmlApplicationContext(java.lang.String[], boolean, org.springframework.context.ApplicationContext)实现如下:
public FileSystemXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
在使用new FileSystemXmlApplicationContext()方式启动Spring时,会进入如上的refresh()中。
1.3.2 refresh
org.springframework.context.support.AbstractApplicationContext#refresh的实现如下:
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// 1 Prepare this context for refreshing.
prepareRefresh();
// 2 Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 3 Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// 4 Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// 5 Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// 6 Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// 7 Initialize message source for this context.
initMessageSource();
// 8 Initialize event multicaster for this context.
initApplicationEventMulticaster();
// 9 Initialize other special beans in specific context subclasses.
onRefresh();
// 10 Check for listener beans and register them.
registerListeners();
// 11 Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// 12 Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// 13 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();
contextRefresh.end();
}
}
}
refresh包含的处理流程如下:
.jpg)
1.3.2.1 prepareRefresh
org.springframework.context.support.AbstractApplicationContext#prepareRefresh,主要是加载配置,校验配置,实现如下:
protected void prepareRefresh() {
// Switch to active.
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
// 子类实现,加载配置文件
initPropertySources();
// 校验所有必填属性是否都设置了
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
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<>();
}
1.3.2.2 obtainFreshBeanFactory
org.springframework.context.support.AbstractApplicationContext#obtainFreshBeanFactory获取最新的BeanFactory,org.springframework.context.support.AbstractApplicationContext#obtainFreshBeanFactory的实现如下:
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// abstract方法,刷新BeanFactory,子类实现,执行BeanFactory的配置加载
refreshBeanFactory();
// abstract方法,子类实现,返回BeanFactory
return getBeanFactory();
}
1.3.2.3 prepareBeanFactory
org.springframework.context.support.AbstractApplicationContext#prepareBeanFactory设置BeanFactory的配置属性,实现如下:
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
if (!shouldIgnoreSpel) {
// 如果使用SPEL表达式,设置解析器,SPEL表达式在spring-expression模块实现,后续进行分析
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
}
// 设置类型转换器,后续做进一步的深入分析
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// 加入ApplicationContextAwareProcessor,对应逻辑的处理在1.4节中详细讨论
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
// 忽略这些依赖接口,使用其他方式进行Bean的加载
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.ignoreDependencyInterface(ApplicationStartupAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// 增加ApplicationListenerDetector类型的BeanPostProcessor
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// AOP相关的处理,后续进一步分析
if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// 注册环境Bean到IOC中
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());
}
if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
}
}
1.3.2.4 AbstractApplicationContext
org.springframework.context.support.AbstractApplicationContext#postProcessBeanFactory是Abstract方法,子类在标准的BeanFactory初始化完成后执行操作。
1.3.2.5 invokeBeanFactoryPostProcessors
执行注册的BeanFactoryPostProcessor处理逻辑,实现如下:
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null &&
beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, java.util.List<org.springframework.beans.factory.config.BeanFactoryPostProcessor>)的实现如下:
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
Set<String> processedBeans = new HashSet<>();
// 如果beanFactory是BeanDefinitionRegistry的继承类,则进入下面的逻辑
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
// 如果该postProcessor是BeanDefinitionRegistryPostProcessor类型,执行其postProcessBeanDefinitionRegistry方法,并加入registryProcessors列表中
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
// 非BeanDefinitionRegistryPostProcessor加入regularPostProcessors列表中
regularPostProcessors.add(postProcessor);
}
}
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
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);
}
}
// 获取所有实现了PriorityOrdered和BeanDefinitionRegistryPostProcessor的接口
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 排序接口放到未排序接口的后面
registryProcessors.addAll(currentRegistryProcessors);
// 执行实现了PriorityOrdered接口的postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
// 按照上面的逻辑,执行所有实现了Ordered接口的postProcessBeanDefinitionRegistry方法
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, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
// 最后执行所有其他的实现了BeanDefinitionRegistryPostProcessor的类
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, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
}
// 最后,执行BeanFactoryPostProcessor.postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// 下面,处理所有延迟加载的BeanFactoryPostProcessor的实现类的接口方法
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
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);
}
}
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
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();
}
private static void invokeBeanDefinitionRegistryPostProcessors(
Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry, ApplicationStartup applicationStartup) {
for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
StartupStep postProcessBeanDefRegistry = applicationStartup.start("spring.context.beandef-registry.post-process")
.tag("postProcessor", postProcessor::toString);
postProcessor.postProcessBeanDefinitionRegistry(registry);
postProcessBeanDefRegistry.end();
}
}
1.3.2.6 registerBeanPostProcessors
注册BeanPostProcessor的实现类,实现如下:
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
org.springframework.context.support.PostProcessorRegistrationDelegate#registerBeanPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, org.springframework.context.support.AbstractApplicationContext)实现如下:
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
// 获取所有的BeanPostProcessor的实现类,对与延迟加载的,不触发加载
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
// 增加一个BeanPostProcessorChecker
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered, Ordered, and the rest.
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.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
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.
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
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.
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
1.3.2.7 initMessageSource
这里不做深入的分析。
1.3.2.8 initApplicationEventMulticaster
org.springframework.context.support.AbstractApplicationContext#initApplicationEventMulticaster初始化事件发送器:
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);
}
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
}
}
1.3.2.9 onRefresh
模板方法,子类可以复写,实现自定义的刷新操作。
1.3.2.10 registerListeners
注册Spring事件监听器:
protected void registerListeners() {
// Register statically specified listeners first.
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// Publish early application events now that we finally have a multicaster...
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
1.3.2.11 finishBeanFactoryInitialization
实例化延迟加载的类。
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// 注册包装类型转换类
Register a default embedded value resolver if no BeanFactoryPostProcessor
// (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();
}
1.3.2.12 finishRefresh
初始化监听器,发送ContextRefreshEvent事件:
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches();
// Initialize lifecycle processor for this context.
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
getLifecycleProcessor().onRefresh();
// Publish the final event.
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
if (!NativeDetector.inNativeImage()) {
LiveBeansView.registerApplicationContext(this);
}
}
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
this.lifecycleProcessor =
beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
}
else {
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
defaultProcessor.setBeanFactory(beanFactory);
this.lifecycleProcessor = defaultProcessor;
beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
}
}
1.4 IOC扩展处理点
1.4.1 BeanPostProcessor
org.springframework.beans.factory.config.BeanPostProcessor对Bean初始化过程中进行扩展的点:
public interface BeanPostProcessor {
// Apply this {@code BeanPostProcessor} to the given new bean instance <i>before</i> any bean initialization callbacks (like InitializingBean's {@code afterPropertiesSet} or a custom init-method). The bean will already be populated with property values.
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
// Apply this {@code BeanPostProcessor} to the given new bean instance <i>after</i> any bean initialization callbacks (like InitializingBean's {@code afterPropertiesSet} or a custom init-method). The bean will already be populated with property values.
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
1.4.1.1 ApplicationContextAwareProcessor
org.springframework.context.support.ApplicationContextAwareProcessor为感知IOC信息的BeanPostProcessor,其中回调Aware的实现接口,实现如下:
class ApplicationContextAwareProcessor implements BeanPostProcessor {
private final ConfigurableApplicationContext applicationContext;
private final StringValueResolver embeddedValueResolver;
public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
this.applicationContext = applicationContext;
this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware ||
bean instanceof ApplicationStartupAware)) {
return bean;
}
AccessControlContext acc = null;
if (System.getSecurityManager() != null) {
acc = this.applicationContext.getBeanFactory().getAccessControlContext();
}
if (acc != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareInterfaces(bean);
return null;
}, acc);
}
else {
invokeAwareInterfaces(bean);
}
return bean;
}
// 通过ApplicationContextAwareProcessor处理的接口
private void invokeAwareInterfaces(Object bean) {
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 ApplicationStartupAware) {
((ApplicationStartupAware) bean).setApplicationStartup(this.applicationContext.getApplicationStartup());
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
}
1.4.1.2 ApplicationListenerDetector
org.springframework.context.support.ApplicationListenerDetector用于检测实现了ApplicationListener接口的Bean,实现如下:
class ApplicationListenerDetector implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor {
private final transient AbstractApplicationContext applicationContext;
// 使用transient的变量不会进行序列化
private final transient Map<String, Boolean> singletonNames = new ConcurrentHashMap<>(256);
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
// 将所有ApplicationListener的实现类放入singletonNames类中,放入类名称和是否是单例类
if (ApplicationListener.class.isAssignableFrom(beanType)) {
this.singletonNames.put(beanName, beanDefinition.isSingleton());
}
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof ApplicationListener) {
Boolean flag = this.singletonNames.get(beanName);
if (Boolean.TRUE.equals(flag)) {
// 只将单例类放入IOC的ApplicationListener列表中
this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
}
else if (Boolean.FALSE.equals(flag)) {
this.singletonNames.remove(beanName);
}
}
return bean;
}
// 在Bean销毁前,将所有的事件发送器列表清空
@Override
public void postProcessBeforeDestruction(Object bean, String beanName) {
if (bean instanceof ApplicationListener) {
try {
ApplicationEventMulticaster multicaster = this.applicationContext.getApplicationEventMulticaster();
multicaster.removeApplicationListener((ApplicationListener<?>) bean);
multicaster.removeApplicationListenerBean(beanName);
}
catch (IllegalStateException ex) {
// ApplicationEventMulticaster not initialized yet - no need to remove a listener
}
}
}
@Override
public boolean requiresDestruction(Object bean) {
return (bean instanceof ApplicationListener);
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof ApplicationListenerDetector &&
this.applicationContext == ((ApplicationListenerDetector) other).applicationContext));
}
@Override
public int hashCode() {
return ObjectUtils.nullSafeHashCode(this.applicationContext);
}
}
org.springframework.context.ApplicationListener接口进行事件的监听,实现如下:
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
// 处理Spring事件
void onApplicationEvent(E event);
// 创建新的ApplicationListener
static <T> ApplicationListener<PayloadApplicationEvent<T>> forPayload(Consumer<T> consumer) {
return event -> consumer.accept(event.getPayload());
}
}
ApplicationListenerDetector实现了DestructionAwareBeanPostProcessor和MergedBeanDefinitionPostProcessor接口。
1.4.1.3 DestructionAwareBeanPostProcessor
org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor接口添加Bean销毁时的处理逻辑,实现如下:
public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor {
// 在Bean销毁前执行
void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException;
// 判断这个Bean是否需要执行这个BeanPostProcessor
default boolean requiresDestruction(Object bean) {
return true;
}
}
1.4.1.4 MergedBeanDefinitionPostProcessor
org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor实现Bean定义的合并处理等操作,@Autowired注解的解析类即是实现了这个接口,实现如下:
public interface MergedBeanDefinitionPostProcessor extends BeanPostProcessor {
// 处理Bean定义
void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName);
// A notification that the bean definition for the specified name has been reset, and that this post-processor should clear any metadata for the affected bean.
default void resetBeanDefinition(String beanName) {
}
}
1.4.1.5 BeanPostProcessorChecker
org.springframework.context.support.PostProcessorRegistrationDelegate.BeanPostProcessorChecker是PostProcessorRegistrationDelegate中的一个内部类,用于打印不能被所有BeanPostProcessor处理的类信息,产生这种情况的原因主要是BeanPostProcessor的实现类存在延迟加载情形,实现如下:
private static final class BeanPostProcessorChecker implements BeanPostProcessor {
private static final Log logger = LogFactory.getLog(BeanPostProcessorChecker.class);
private final ConfigurableListableBeanFactory beanFactory;
private final int beanPostProcessorTargetCount;
public BeanPostProcessorChecker(ConfigurableListableBeanFactory beanFactory, int beanPostProcessorTargetCount) {
this.beanFactory = beanFactory;
// beanPostProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length
this.beanPostProcessorTargetCount = beanPostProcessorTargetCount;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
// 如果Bean不是BeanPostProcessor的子类,不是基础Bean,存在BeanPostProcessor的实现延迟加载类
if (!(bean instanceof BeanPostProcessor) && !isInfrastructureBean(beanName) &&
this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {
if (logger.isInfoEnabled()) {
logger.info("Bean '" + beanName + "' of type [" + bean.getClass().getName() +
"] is not eligible for getting processed by all BeanPostProcessors " +
"(for example: not eligible for auto-proxying)");
}
}
return bean;
}
// 判断一个bean是否是基础Bean,如AspectJCachingConfiguration类
private boolean isInfrastructureBean(@Nullable String beanName) {
if (beanName != null && this.beanFactory.containsBeanDefinition(beanName)) {
BeanDefinition bd = this.beanFactory.getBeanDefinition(beanName);
return (bd.getRole() == RootBeanDefinition.ROLE_INFRASTRUCTURE);
}
return false;
}
}
1.4.2 Aware接口
org.springframework.beans.factory.Aware一个标记超接口,指示一个bean有资格通过回调样式的方法被Spring容器通知到一个特定的框架对象。实际的方法签名由各个子接口决定,但通常应该只包含一个接受单个参数的返回void的方法,定义如下:
public interface EnvironmentAware extends Aware {
void setEnvironment(Environment environment);
}
Aware的继承子类
ApplicationEventPublisherAware (org.springframework.context)
EventPublicationInterceptor (org.springframework.context.event)
ServletContextAware (org.springframework.web.context)
ContentNegotiationManagerFactoryBean (org.springframework.web.accept)
ServletContextAttributeFactoryBean (org.springframework.web.context.support)
WebApplicationObjectSupport (org.springframework.web.context.support)
GenericFilterBean (org.springframework.web.filter)
DelegatingFilterProxy (org.springframework.web.filter)
OncePerRequestFilter (org.springframework.web.filter)
HiddenHttpMethodFilter (org.springframework.web.filter)
RelativeRedirectFilter (org.springframework.web.filter)
HttpPutFormContentFilter (org.springframework.web.filter)
CorsFilter (org.springframework.web.filter)
CharacterEncodingFilter (org.springframework.web.filter)
RequestContextFilter (org.springframework.web.filter)
ForwardedHeaderFilter (org.springframework.web.filter)
MultipartFilter (org.springframework.web.multipart.support)
FormContentFilter (org.springframework.web.filter)
ShallowEtagHeaderFilter (org.springframework.web.filter)
AbstractRequestLoggingFilter (org.springframework.web.filter)
ServletContextParameterFactoryBean (org.springframework.web.context.support)
CommonsMultipartResolver (org.springframework.web.multipart.commons)
ServletContextAttributeExporter (org.springframework.web.context.support)
MessageSourceAware (org.springframework.context)
ResourceLoaderAware (org.springframework.context)
SortedResourcesFactoryBean (org.springframework.jdbc.config)
ConfigurationClassPostProcessor (org.springframework.context.annotation)
ReloadableResourceBundleMessageSource (org.springframework.context.support)
ScriptFactoryPostProcessor (org.springframework.scripting.support)
ClassPathScanningCandidateComponentProvider (org.springframework.context.annotation)
ApplicationStartupAware (org.springframework.context)
ConfigurationClassPostProcessor (org.springframework.context.annotation)
NotificationPublisherAware (org.springframework.jmx.export.notification)
EnvironmentAware (org.springframework.context)
ConfigurationClassPostProcessor (org.springframework.context.annotation)
PropertySourcesPlaceholderConfigurer (org.springframework.context.support)
GenericFilterBean (org.springframework.web.filter)
MBeanExportConfiguration (org.springframework.context.annotation)
BeanFactoryAware (org.springframework.beans.factory)
AbstractBeanFactoryAwareAdvisingPostProcessor (org.springframework.aop.framework.autoproxy)
AbstractBeanFactoryBasedTargetSourceCreator (org.springframework.aop.framework.autoproxy.target)
PropertyPathFactoryBean (org.springframework.beans.factory.config)
TransactionProxyFactoryBean (org.springframework.transaction.interceptor)
SimpleBeanFactoryAwareAspectInstanceFactory (org.springframework.aop.config)
PersistenceExceptionTranslationInterceptor (org.springframework.dao.support)
BeanFactoryDataSourceLookup (org.springframework.jdbc.datasource.lookup)
ScheduledAnnotationBeanPostProcessor (org.springframework.scheduling.annotation)
GroovyScriptFactory (org.springframework.scripting.groovy)
CommonAnnotationBeanPostProcessor (org.springframework.context.annotation)
AbstractBeanFactoryPointcutAdvisor (org.springframework.aop.support)
TransactionAspectSupport (org.springframework.transaction.interceptor)
ServiceLocatorFactoryBean (org.springframework.beans.factory.config)
MethodLocatingFactoryBean (org.springframework.aop.config)
MBeanExporter (org.springframework.jmx.export)
AbstractBeanFactoryBasedTargetSource (org.springframework.aop.target)
GenericTypeAwareAutowireCandidateResolver (org.springframework.beans.factory.support)
AbstractAutoProxyCreator (org.springframework.aop.framework.autoproxy)
DefaultLifecycleProcessor (org.springframework.context.support)
AspectJExpressionPointcutAdvisor (org.springframework.aop.aspectj)
AutowiredAnnotationBeanPostProcessor (org.springframework.beans.factory.annotation)
ScopedProxyFactoryBean (org.springframework.aop.scope)
LoadTimeWeaverAwareProcessor (org.springframework.context.weaving)
WebAsyncTask (org.springframework.web.context.request.async)
BeanConfigurerSupport (org.springframework.beans.factory.wiring)
AnnotationJmxAttributeSource (org.springframework.jmx.export.annotation)
ScriptFactoryPostProcessor (org.springframework.scripting.support)
AbstractApplicationEventMulticaster (org.springframework.context.event)
AbstractFactoryBean (org.springframework.beans.factory.config)
EnhancedConfiguration in ConfigurationClassEnhancer (org.springframework.context.annotation)
AsyncExecutionAspectSupport (org.springframework.aop.interceptor)
CacheAspectSupport (org.springframework.cache.interceptor)
MethodInvokingBean (org.springframework.beans.factory.config)
ProxyFactoryBean (org.springframework.aop.framework)
JndiObjectFactoryBean (org.springframework.jndi)
AsyncAnnotationAdvisor (org.springframework.scheduling.annotation)
PlaceholderConfigurerSupport (org.springframework.beans.factory.config)
AbstractJaxWsServiceExporter (org.springframework.remoting.jaxws)
RequiredAnnotationBeanPostProcessor (org.springframework.beans.factory.annotation)
MBeanExportConfiguration (org.springframework.context.annotation)
CacheProxyFactoryBean (org.springframework.cache.interceptor)
AspectJExpressionPointcut (org.springframework.aop.aspectj)
ImportAware (org.springframework.context.annotation)
AbstractAsyncConfiguration (org.springframework.scheduling.annotation)
AbstractCachingConfiguration (org.springframework.cache.annotation)
LoadTimeWeavingConfiguration (org.springframework.context.annotation)
MBeanExportConfiguration (org.springframework.context.annotation)
AbstractTransactionManagementConfiguration (org.springframework.transaction.annotation)
EmbeddedValueResolverAware (org.springframework.context)
ScheduledAnnotationBeanPostProcessor (org.springframework.scheduling.annotation)
NameMatchTransactionAttributeSource (org.springframework.transaction.interceptor)
AbstractFallbackTransactionAttributeSource (org.springframework.transaction.interceptor)
FormattingConversionServiceFactoryBean (org.springframework.format.support)
FormattingConversionService (org.springframework.format.support)
MethodMapTransactionAttributeSource (org.springframework.transaction.interceptor)
EmbeddedValueResolutionSupport (org.springframework.context.support)
ServletConfigAware (org.springframework.web.context)
BootstrapContextAware (org.springframework.jca.context)
WorkManagerTaskExecutor (org.springframework.jca.work)
LoadTimeWeaverAware (org.springframework.context.weaving)
AspectJWeavingEnabler (org.springframework.context.weaving)
BeanClassLoaderAware (org.springframework.beans.factory)
MBeanProxyFactoryBean (org.springframework.jmx.access)
DefaultContextLoadTimeWeaver (org.springframework.context.weaving)
BshScriptFactory (org.springframework.scripting.bsh)
LocalStatelessSessionProxyFactoryBean (org.springframework.ejb.access)
StandardScriptFactory (org.springframework.scripting.support)
ConcurrentMapCacheManager (org.springframework.cache.concurrent)
GroovyScriptFactory (org.springframework.scripting.groovy)
MBeanServerConnectionFactoryBean (org.springframework.jmx.support)
MBeanExporter (org.springframework.jmx.export)
ServiceLoaderFactoryBean (org.springframework.beans.factory.serviceloader)
RmiProxyFactoryBean (org.springframework.remoting.rmi)
ServiceFactoryBean (org.springframework.beans.factory.serviceloader)
AbstractSingletonProxyFactoryBean (org.springframework.aop.framework)
CustomScopeConfigurer (org.springframework.beans.factory.config)
RemotingSupport (org.springframework.remoting.support)
CustomAutowireConfigurer (org.springframework.beans.factory.annotation)
MBeanClientInterceptor (org.springframework.jmx.access)
AbstractHttpInvokerRequestExecutor (org.springframework.remoting.httpinvoker)
JndiRmiProxyFactoryBean (org.springframework.remoting.rmi)
ScriptFactoryPostProcessor (org.springframework.scripting.support)
AbstractApplicationEventMulticaster (org.springframework.context.event)
AbstractFactoryBean (org.springframework.beans.factory.config)
ResourceBundleMessageSource (org.springframework.context.support)
ResourceBundleThemeSource (org.springframework.ui.context.support)
SimpleRemoteStatelessSessionProxyFactoryBean (org.springframework.ejb.access)
ProxyProcessorSupport (org.springframework.aop.framework)
InterfaceBasedMBeanInfoAssembler (org.springframework.jmx.export.assembler)
MethodMapTransactionAttributeSource (org.springframework.transaction.interceptor)
MethodInvokingBean (org.springframework.beans.factory.config)
FieldRetrievingFactoryBean (org.springframework.beans.factory.config)
JaxWsPortClientInterceptor (org.springframework.remoting.jaxws)
ProxyFactoryBean (org.springframework.aop.framework)
BshScriptEvaluator (org.springframework.scripting.bsh)
JndiObjectFactoryBean (org.springframework.jndi)
LoadTimeWeavingConfiguration (org.springframework.context.annotation)
MethodInvokingRunnable (org.springframework.scheduling.support)
AspectJWeavingEnabler (org.springframework.context.weaving)
ServiceListFactoryBean (org.springframework.beans.factory.serviceloader)
ConfigurationClassPostProcessor (org.springframework.context.annotation)
GroovyScriptEvaluator (org.springframework.scripting.groovy)
Jackson2ObjectMapperFactoryBean (org.springframework.http.converter.json)
StandardScriptEvaluator (org.springframework.scripting.support)
AbstractServiceLoaderBasedFactoryBean (org.springframework.beans.factory.serviceloader)
BeanNameAware (org.springframework.beans.factory)
ExecutorConfigurationSupport (org.springframework.scheduling.concurrent)
ConcurrentMapCacheFactoryBean (org.springframework.cache.concurrent)
PropertyPathFactoryBean (org.springframework.beans.factory.config)
PlaceholderConfigurerSupport (org.springframework.beans.factory.config)
AbstractRefreshableConfigApplicationContext (org.springframework.context.support)
ScheduledAnnotationBeanPostProcessor (org.springframework.scheduling.annotation)
GenericFilterBean (org.springframework.web.filter)
DefaultAdvisorAutoProxyCreator (org.springframework.aop.framework.autoproxy)
AbstractMessageEndpointFactory (org.springframework.jca.endpoint)
TaskExecutorFactoryBean (org.springframework.scheduling.config)
FieldRetrievingFactoryBean (org.springframework.beans.factory.config)
ApplicationContextAware (org.springframework.context)
ScheduledAnnotationBeanPostProcessor (org.springframework.scheduling.annotation)
Jackson2ObjectMapperFactoryBean (org.springframework.http.converter.json)
LiveBeansView (org.springframework.context.support)
EventListenerMethodProcessor (org.springframework.context.event)
LocalValidatorFactoryBean (org.springframework.validation.beanvalidation)
ApplicationObjectSupport (org.springframework.context.support)
1.4.2.1 EnvironmentAware
org.springframework.context.EnvironmentAware可以感知IOC环境信息的变化,实现如下:
public interface EnvironmentAware extends Aware {
void setEnvironment(Environment environment);
}
1.4.2.2 EmbeddedValueResolverAware
org.springframework.context.EmbeddedValueResolverAware接口感知IOC容器使用的字符串配置解析逻辑,实现如下:
public interface EmbeddedValueResolverAware extends Aware {
//
void setEmbeddedValueResolver(StringValueResolver resolver);
}
1.4.2.3 ResourceLoaderAware
org.springframework.context.ResourceLoaderAware感知IOC容器的配置加载实现逻辑,实现如下:
public interface ResourceLoaderAware extends Aware {
void setResourceLoader(ResourceLoader resourceLoader);
}
1.4.2.4 ApplicationEventPublisherAware
org.springframework.context.ApplicationEventPublisherAware感知Spring事件发布逻辑,实现如下:
public interface ApplicationEventPublisherAware extends Aware {
void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher);
}
1.4.2.5 MessageSourceAware
public interface MessageSourceAware extends Aware {
void setMessageSource(MessageSource messageSource);
}
1.4.2.6 ApplicationStartupAware
public interface ApplicationStartupAware extends Aware {
void setApplicationStartup(ApplicationStartup applicationStartup);
}
1.4.2.7 ApplicationContextAware
org.springframework.context.ApplicationContextAware使用比较广泛,可以获取IOC容器的引用,用于获取上下文信息:
public interface ApplicationContextAware extends Aware {
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
1.4.2.8 BeanClassLoaderAware
org.springframework.beans.factory.BeanClassLoaderAware感知ClassLoader的信息:
public interface BeanClassLoaderAware extends Aware {
// Callback that supplies the bean {@link ClassLoader class loader} to a bean instance.
void setBeanClassLoader(ClassLoader classLoader);
}
1.4.2.9 BeanFactoryAware
org.springframework.beans.factory.BeanFactoryAware感知IOC信息:
public interface BeanFactoryAware extends Aware {
// Callback that supplies the owning factory to a bean instance.
void setBeanFactory(BeanFactory beanFactory) throws BeansException;
}
1.4.2.10 LoadTimeWeaverAware
org.springframework.context.weaving.接受对于LoadTimeWeaver的引用:
public interface LoadTimeWeaverAware extends Aware {
//
void setLoadTimeWeaver(LoadTimeWeaver loadTimeWeaver);
}
1.4.3 AliasRegistry
org.springframework.core.AliasRegistry为通用接口,定义别名注册的逻辑,实现如下:
public interface AliasRegistry {
// Given a name, register an alias for it.
void registerAlias(String name, String alias);
// Remove the specified alias from this registry.
void removeAlias(String alias);
// Determine whether the given name is defined as an alias (as opposed to the name of an actually registered component).
boolean isAlias(String name);
// Return the aliases for the given name, if defined.
String[] getAliases(String name);
}
AliasRegistry的子类如下:
SimpleAliasRegistry (org.springframework.core)
DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
FactoryBeanRegistrySupport (org.springframework.beans.factory.support)
AbstractBeanFactory (org.springframework.beans.factory.support)
AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
DefaultListableBeanFactory (org.springframework.beans.factory.support)
XmlBeanFactory (org.springframework.beans.factory.xml)
SimpleBeanDefinitionRegistry (org.springframework.beans.factory.support)
BeanDefinitionRegistry (org.springframework.beans.factory.support)
SimpleBeanDefinitionRegistry (org.springframework.beans.factory.support)
DefaultListableBeanFactory (org.springframework.beans.factory.support)
XmlBeanFactory (org.springframework.beans.factory.xml)
GenericApplicationContext (org.springframework.context.support)
GenericXmlApplicationContext (org.springframework.context.support)
StaticApplicationContext (org.springframework.context.support)
StaticWebApplicationContext (org.springframework.web.context.support)
GenericWebApplicationContext (org.springframework.web.context.support)
ResourceAdapterApplicationContext (org.springframework.jca.context)
GenericGroovyApplicationContext (org.springframework.context.support)
AnnotationConfigApplicationContext (org.springframework.context.annotation)
org.springframework.beans.factory.support.BeanDefinitionRegistry定义了Bean定义注册的接口,实现如下:
public interface BeanDefinitionRegistry extends AliasRegistry {
// Register a new bean definition with this registry.
void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException;
// Remove the BeanDefinition for the given name.
void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
// Return the BeanDefinition for the given bean name.
BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
// Check if this registry contains a bean definition with the given name.
boolean containsBeanDefinition(String beanName);
// Return the names of all beans defined in this registry.
String[] getBeanDefinitionNames();
// Return the number of beans defined in the registry.
int getBeanDefinitionCount();
// Determine whether the given bean name is already in use within this registry, i.e. whether there is a local bean or alias registered under this name.
boolean isBeanNameInUse(String beanName);
}
1.4.4 BeanFactoryPostProcessor
org.springframework.beans.factory.config.BeanFactoryPostProcessor接口允许自定义修改应用程序上下文的bean定义,调整上下文的基础bean工厂的bean属性值,实现如下:
@FunctionalInterface
public interface BeanFactoryPostProcessor {
// 在标准化启动后修改beanFactory,此时Bean定义已经加载,还没有实例化,此处可以修改Bean的属性
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}
BeanFactoryPostProcessor的子类如下:
AspectJWeavingEnabler (org.springframework.context.weaving)
EventListenerMethodProcessor (org.springframework.context.event)
PropertyResourceConfigurer (org.springframework.beans.factory.config)
PropertyOverrideConfigurer (org.springframework.beans.factory.config)
PlaceholderConfigurerSupport (org.springframework.beans.factory.config)
PropertySourcesPlaceholderConfigurer (org.springframework.context.support)
PropertyPlaceholderConfigurer (org.springframework.beans.factory.config)
PreferencesPlaceholderConfigurer (org.springframework.beans.factory.config)
CustomScopeConfigurer (org.springframework.beans.factory.config)
BeanDefinitionRegistryPostProcessor (org.springframework.beans.factory.support)
ConfigurationClassPostProcessor (org.springframework.context.annotation)
CustomAutowireConfigurer (org.springframework.beans.factory.annotation)
DeprecatedBeanWarner (org.springframework.beans.factory.config)
CustomEditorConfigurer (org.springframework.beans.factory.config)
1.4.4.1 BeanDefinitionRegistryPostProcessor
org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor对标准 BeanFactoryPostProcessor进行扩展,允许在常规BeanFactoryPostProcessor之前做处理,实现如下:
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
// 在BeanFactoryPostProcessor.postProcessBeanFactory前执行
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}