用着spring当然得懂核心技术以及原理啦~~~
话不多说,开干!不定期增加内容。
注:不是跟着书上的内容来的,完全是靠自己一个个方法点进去,分析实现原理
实际上,本文标题应该是 (Spring技术内幕:深入解析Spring架构与设计原理(第2版)【阅读笔记】 与 Spring源码分析)相结合
本文源码来自于spring4.1.3
spring 核心实现
什么是IoC
一个引用自https://www.zhihu.com/question/23277575
的故事
我开了一家薯条店,底下有一百家分店
一开始我懒,让分店自己去炸薯条,反正只要他们按照统一的配方来就好,比如油温170度,炸两分钟
有一天我突然发现油温169度炸出来的薯条更好次,kao!我得打100个电话,告诉分店经理改配方!(就是你要改很多处代码)
有了这次教训,我觉得让总店(就是Spring容器)来统一炸好薯条,然后送到各个分店去,要吃的时候再拿出来炸热一下就ok了
本来是分店自己决定怎么炸薯条的,虽然我给了他们配方,但是最终决定权在他们手上,他们偷偷少炸几秒钟、少放点油,我都管不着,现在我霸道了,把炸薯条权收归中央,这不就是控制反转(IOC)了吗?
换个角度讲,现在分店的薯条,都是我总店炸好送过去的,分店依赖总店的薯条,这不就是依赖注入了吗?
IoC 容器系列的设计与实现
BeanFactory
BeanFactory
是容器的最基本接口定义。
public interface BeanFactory {
String FACTORY_BEAN_PREFIX = "&";
// 获取指定名字的bean
Object getBean(String name) throws BeansException;
// 获取指定名字与类型的bean
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
// 获取指定类型的bean
<T> T getBean(Class<T> requiredType) throws BeansException;
// 获取指定名字的bean并覆盖bean的默认参数
Object getBean(String name, Object... args) throws BeansException;
// 获取指定类型的bean并覆盖bean的默认参数
<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
// 判断IOC容器中是否有指定名字的bean
boolean containsBean(String name);
// 判断指定名字的bean是否为单例
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
// 判断指定名字的bean类型是否匹配
boolean isTypeMatch(String name, Class<?> targetType) throws NoSuchBeanDefinitionException;
// 获取指定名字的bean的类型
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
// 获取指定名字的bean的别名
String[] getAliases(String name);
}
IOC容器的初始化过程
BeanDefinition的Resource定位
首先定义一个Resource来定位容器使用BeanDefinition。
常见几种读取方式
-
FileSystemXmlApplicationContext(从文件系统载入Resource)
-
ClassPathXmlApplicationContext(从classpath载入Resource)
-
XmlWebApplicationContext(从web容器中载入Resource)
BeanDefinition的载入和解析
BeanDefinition在IoC容器中的注册
ApplicationContext
AbstractApplicationContext
refresh()
refresh
方法的作用是加载spring容器
首先看一下refresh
内部的执行过程
public void refresh() throws BeansException, IllegalStateException {
// 加上synchronized,防止出现竞态条件(初始化的过程中被销毁)
synchronized (this.startupShutdownMonitor) {
//
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
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) {
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;
}
}
}
第一步:刷新beanFactory之前的初始化(prepareRefresh):
protected void prepareRefresh() {
// 获取启动容器时系统时间
this.startupDate = System.currentTimeMillis();
// 确定启动的标识,this.active是AtomicBoolean类型
this.active.set(true);
if (logger.isInfoEnabled()) {
logger.info("Refreshing " + this);
}
// 初始化上下文环境,在AbstractApplicationContext中没有具体实现
initPropertySources();
// 验证必要的参数(initPropertySources方法初始化后的参数)是否完整
getEnvironment().validateRequiredProperties();
}
第二步:获取刷新后的beanFactory(obtainFreshBeanFactory)
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 刷新beanFactory,在AbstractApplicationContext中没有具体实现,具体实现在AbstractRefreshableApplicationContext与GenericApplicationContext中实现
refreshBeanFactory();
// 获取刷新后的beanFactory,在AbstractApplicationContext中没有具体实现,具体实现在AbstractRefreshableApplicationContext与GenericApplicationContext中实现
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
bean的载入过程(refreshBeanFactory),以AbstractRefreshableApplicationContext类为例
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
// 载入
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
loadBeanDefinitions载入、解析文件
- XmlWebApplicationContext
解析xml文件的各种标签、扫描包路径将有@Component注解的都注册到ioc容器中... - AnnotationConfigWebApplicationContext
- GroovyWebApplicationContext
第三步:初始化刷新后的beanFactory(prepareBeanFactory)
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 设置类加载器
beanFactory.setBeanClassLoader(getClassLoader());
// 设置表达式解析器,比如解析SpEL表达式
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
// 添加属性编辑器,比如某些特定格式的转换
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// [详见BeanPostProcessor](#BeanPostProcessor),主要作用:修改bean对象(初始化之前和初始化之后)
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
// 在AbstractAutowireCapableBeanFactory类中有具体实现,作用:忽略自动装配的接口(因为在bean初始化之前会调用ApplicationContextAwareProcessor.postProcessBeforeInitialization方法,就已经做了依赖处理)
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
// 注册依赖
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// 对Aspect的支持
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()));
}
// 对系统变量进行注入
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());
}
}
DefaultListableBeanFactory
BeanPostProcessor
AbstractAutowireCapableBeanFactory
PostProcessor 后置处理器
第四步:允许在bean加载完后,初始化前对beanFactory进行修改(postProcessBeanFactory),在其子类中实现自定义的需求
以AbstractRefreshableWebApplicationContext
类为例
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig));
beanFactory.ignoreDependencyInterface(ServletContextAware.class);
beanFactory.ignoreDependencyInterface(ServletConfigAware.class);
// 注册request/session作用域
WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig);
}
第五步:调用beanFactory的后置处理器(invokeBeanFactoryPostProcessors)
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// 调用BeanFactory后置处理器
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
}
@Override
public void addBeanFactoryPostProcessor(BeanFactoryPostProcessor beanFactoryPostProcessor) {
this.beanFactoryPostProcessors.add(beanFactoryPostProcessor);
}
public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
return this.beanFactoryPostProcessors;
}
详见PostProcessorRegistrationDelegate
类中的部分方法
/**
* beanFactoryPostProcessors,spring的扩展之一,查看springboot的加载过程时
* 会发现调用ApplicationContextInitializer.initialize
* 通过调用AbstractApplicationContext.addBeanFactoryPostProcessor,
* 将自定义的beanFactoryPostProcessor加入beanFactoryPostProcessors中
*/
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
Set<String> processedBeans = new HashSet<String>();
// 首先处理BeanDefinitionRegistryPostProcessor
// BeanDefinitionRegistryPostProcessor的作用是注册bean
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// 普通的后置处理器
List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
// 需要自定义注册bean的后置处理器(下文有解释)
List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =
new LinkedList<BeanDefinitionRegistryPostProcessor>();
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
// 判断是否为需要自定义注册bean的后置处理器
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryPostProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
// 调用自定义注册的方法
// example:
// 在mybatis里
// MapperScannerConfigurer.java
// |-- postProcessBeanDefinitionRegistry
// 会把dao的class(真实的class)改成"MapperFactoryBean.class",
// 也就是所有的DAO都从MapperFactoryBean里获取,源码:ClassPathMapperScanner.java - line 171
// definition.setBeanClass(MapperFactoryBean.class);
// 在dubbo里
// ServiceAnnotationBeanPostProcessor.java
// |-- postProcessBeanDefinitionRegistry
// 解析package路径,注册bean
registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
registryPostProcessors.add(registryPostProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
// 获取所有BeanDefinitionRegistryPostProcessor类型的后置处理器的名字
// 详情见【spring源码解析-DefaultListableBeanFactory】
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// 1.选出实现了PriorityOrdered接口的bean(优先排序、调用)
List<BeanDefinitionRegistryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
for (String ppName : postProcessorNames) {
// 如果实现了PriorityOrdered接口
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
OrderComparator.sort(priorityOrderedPostProcessors);
registryPostProcessors.addAll(priorityOrderedPostProcessors);
// 注册bean到spring容器中
invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);
// 2.选出实现了Ordered接口的bean(优先排序、调用)
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
List<BeanDefinitionRegistryPostProcessor> orderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
for (String ppName : postProcessorNames) {
// 如果实现了Ordered接口,因为PriorityOrdered继承Ordered,所以要把已经处理过的排除
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
OrderComparator.sort(orderedPostProcessors);
registryPostProcessors.addAll(orderedPostProcessors);
invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);
// 接下来就是处理未经过排序的BeanDefinitionRegistryPostProcessor
boolean reiterate = true;
// 为什么要多一层while循环呢?
// 因为在每次调用postProcessBeanDefinitionRegistry的时候,可能会增加bean
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class);
registryPostProcessors.add(pp);
processedBeans.add(ppName);
pp.postProcessBeanDefinitionRegistry(registry);
reiterate = true;
}
}
}
// 调用BeanFactory后置处理器,作用为【对BeanDefinition对象进行修改】
invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// 调用BeanFactory后置处理器
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// 获取所有实现了BeanFactoryPostProcessor类型的后置处理器的名字
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
List<String> orderedPostProcessorNames = new ArrayList<String>();
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
for (String ppName : postProcessorNames) {
// 如果当前bean name在已经处理的的名字列表中
if (processedBeans.contains(ppName)) {
// 在上面已经调用过后置处理器方法的就不用再处理
}
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);
}
}
// 首先调用实现了PriorityOrdered接口的BeanFactoryPostProcessors
OrderComparator.sort(priorityOrderedPostProcessors);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 再调用实现了Ordered接口的BeanFactoryPostProcessors
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
OrderComparator.sort(orderedPostProcessors);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// 最后调用其他BeanFactoryPostProcessors
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
}
/**
* Invoke the given BeanFactoryPostProcessor beans.
*/
private static void invokeBeanFactoryPostProcessors(
Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {
for (BeanFactoryPostProcessor postProcessor : postProcessors) {
postProcessor.postProcessBeanFactory(beanFactory);
}
}
BeanFactoryPostProcessor 与 BeanDefinitionRegistryPostProcessor的区别
首先看一下BeanFactoryPostProcessor
的源码
public interface BeanFactoryPostProcessor {
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}
postProcessBeanFactory
方法的作用在上文(第四步)也提到过,可以对beanFactory进行修改。
以下是BeanDefinitionRegistryPostProcessor
的源码
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}
BeanDefinitionRegistryPostProcessor
继承自BeanFactoryPostProcessor
,提供了postProcessBeanDefinitionRegistry
方法,作用是可以根据自己的需求注册bean。
第六步:添加bean的后置处理器(registerBeanPostProcessors)
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
详见PostProcessorRegistrationDelegate
类中的部分方法
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));
// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
List<String> orderedPostProcessorNames = new ArrayList<String>();
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
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);
}
}
// 跟上面注册BeanFactoryPostProcessor一样,先注册实现了PriorityOrdered接口的BeanPostProcessor
OrderComparator.sort(priorityOrderedPostProcessors);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// 注册实现了Ordered接口的BeanPostProcessor
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
OrderComparator.sort(orderedPostProcessors);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// 注册其他没有排序的BeanPostProcessor
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
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.
OrderComparator.sort(internalPostProcessors);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
/**
* Register the given BeanPostProcessor beans.
*/
private static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
for (BeanPostProcessor postProcessor : postProcessors) {
beanFactory.addBeanPostProcessor(postProcessor);
}
}
MergedBeanDefinitionPostProcessor
这个接口的作用是作为所有BeanPostProcessor加载完成之后的一个回调
public interface MergedBeanDefinitionPostProcessor extends BeanPostProcessor {
/**
* Post-process the given merged bean definition for the specified bean.
* @param beanDefinition the merged bean definition for the bean
* @param beanType the actual type of the managed bean instance
* @param beanName the name of the bean
*/
void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName);
}
BeanPostProcessor 和 BeanFactoryPostProcessor的区别
BeanPostProcessor
是针对于某个bean进行处理,BeanFactoryPostProcessor
是针对于整个beanFactory(bean工厂)进行处理。
第七步:国际化支持(initMessageSource)
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 如果存在messageSource,也就是说 用户 自定义过名字为messageSource的bean时
// containsLocalBean和containsBean的区别,下面解释
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
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;
// 如果父级MessageSource为null,就设置,如果存在就不会再设置了
if (hms.getParentMessageSource() == null) {
// 设置父级MessageSource
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (logger.isDebugEnabled()) {
logger.debug("Using MessageSource [" + this.messageSource + "]");
}
}
else {
// 默认设置为DelegatingMessageSource
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME +
"': using default [" + this.messageSource + "]");
}
}
}
containsLocalBean
和containsBean
的区别
在AbstractBeanFactory
中的实现,可以看出containsLocalBean
只是在当前beanFactory中查找bean,而containsBean
还会在父级beanFactory
中查找。
public boolean containsLocalBean(String name) {
String beanName = transformedBeanName(name);
return ((containsSingleton(beanName) || containsBeanDefinition(beanName)) &&
(!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName)));
}
public boolean containsBean(String name) {
String beanName = transformedBeanName(name);
if (containsSingleton(beanName) || containsBeanDefinition(beanName)) {
return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name));
}
// Not found -> check parent.
BeanFactory parentBeanFactory = getParentBeanFactory();
return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name)));
}
第八步:事件广播(initApplicationEventMulticaster)
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 如果存在applicationEventMulticaster,也就是说 用户 自定义过名字为applicationEventMulticaster的bean时
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isDebugEnabled()) {
logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
// 用户未自定义过,默认用SimpleApplicationEventMulticaster
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
"': using default [" + this.applicationEventMulticaster + "]");
}
}
}
第九步:初始化特定上下文子类中的其他特殊bean(onRefresh)
默认没有实现
在AbstractRefreshableWebApplicationContext
类中的实现如下
protected void onRefresh() {
this.themeSource = UiApplicationContextUtils.initThemeSource(this);
}
UiApplicationContextUtils
类中的initThemeSource
方法,
总而言之,onRefresh
的具体作用就是初始化特定上下文子类中的其他特殊bean
public static ThemeSource initThemeSource(ApplicationContext context) {
if (context.containsLocalBean(THEME_SOURCE_BEAN_NAME)) {
ThemeSource themeSource = context.getBean(THEME_SOURCE_BEAN_NAME, ThemeSource.class);
// Make ThemeSource aware of parent ThemeSource.
if (context.getParent() instanceof ThemeSource && themeSource instanceof HierarchicalThemeSource) {
HierarchicalThemeSource hts = (HierarchicalThemeSource) themeSource;
if (hts.getParentThemeSource() == null) {
// Only set parent context as parent ThemeSource if no parent ThemeSource
// registered already.
hts.setParentThemeSource((ThemeSource) context.getParent());
}
}
if (logger.isDebugEnabled()) {
logger.debug("Using ThemeSource [" + themeSource + "]");
}
return themeSource;
}
else {
// Use default ThemeSource to be able to accept getTheme calls, either
// delegating to parent context's default or to local ResourceBundleThemeSource.
HierarchicalThemeSource themeSource = null;
if (context.getParent() instanceof ThemeSource) {
themeSource = new DelegatingThemeSource();
themeSource.setParentThemeSource((ThemeSource) context.getParent());
}
else {
themeSource = new ResourceBundleThemeSource();
}
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate ThemeSource with name '" + THEME_SOURCE_BEAN_NAME +
"': using default [" + themeSource + "]");
}
return themeSource;
}
}
第十步:注册监听器(registerListeners)
applicationEventMulticaster
在第八步中已经初始化过;
protected void registerListeners() {
// 在spring启动的过程中,会有部分监听器需要加载
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 获取实现ApplicationListener接口的bean(用户自定义的监听器)
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String lisName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(lisName);
}
}
ApplicationEventMulticaster getApplicationEventMulticaster() throws IllegalStateException {
if (this.applicationEventMulticaster == null) {
throw new IllegalStateException("ApplicationEventMulticaster not initialized - " +
"call 'refresh' before multicasting events via the context: " + this);
}
return this.applicationEventMulticaster;
}
spring会通过
addApplicationListener
加载监听器(非用户自定义的监听器)
@Override
public void addApplicationListener(ApplicationListener<?> listener) {
if (this.applicationEventMulticaster != null) {
this.applicationEventMulticaster.addApplicationListener(listener);
}
else {
this.applicationListeners.add(listener);
}
}
第十一步:实例化剩余非懒加载的单例(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));
}
// 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();
// 实例化剩余非懒加载的单例
// 在此之前,所有的bean都是以beanDefinition的形式存在,类似于前端的虚拟DOM
beanFactory.preInstantiateSingletons();
}
DefaultListableBeanFactory
中默认实现
@Override
public void freezeConfiguration() {
this.configurationFrozen = true;
this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames);
}
@Override
public void preInstantiateSingletons() throws BeansException {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Pre-instantiating singletons in " + this);
}
// 所有bean名字
List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);
for (String beanName : beanNames) {
// 获取合并后的RootBeanDefinition
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// bean不是抽象,是单例,不是懒加载
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
// 判断是否实现了FactoryBean接口,下文付源码
if (isFactoryBean(beanName)) {
final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
// 是否强制实例化
boolean isEagerInit;
// 判断是否开启了安全校验,如果factoryBean实现了SmartFactoryBean
// SmartFactoryBean:spring内部用,平时基本用不到
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return ((SmartFactoryBean<?>) factory).isEagerInit();
}
}, getAccessControlContext());
}
else {
// 如果没实现SmartFactoryBean,就直接为不需要强制实例化
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
// getBean目的也就是实例化
getBean(beanName);
}
}
else {
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
smartSingleton.afterSingletonsInstantiated();
return null;
}
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
AbstractBeanFactory.isFactoryBean
public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException {
// 获取bean的真实名字
String beanName = transformedBeanName(name);
// 获取bean对象
Object beanInstance = getSingleton(beanName, false);
// 不为null时,返回是否实现了FactoryBean
if (beanInstance != null) {
return (beanInstance instanceof FactoryBean);
}
// 在上面getSingleton里有加锁,所以到这一步之前,可能又被别的线程又注册了某些bean,所以这里还要判断一下是否被注册过
else if (containsSingleton(beanName)) {
// 如果已经注册,直接返回不是FactoryBean,在这里就可以看到,FactoryBean的作用就是增强Bean的能力
return false;
}
// 如果在当前BeanFactory中没有发现,就去父BeanFactory找
if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name);
}
// 上述条件都不满足,即:bean还未注册,也没有父级BeanFactory,那就去mdb里获取类型
// getMergedLocalBeanDefinition在上面已经分析过,获取合并后的RootBeanDefinition
return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName));
}
protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) {
// 预测bean的类型
Class<?> beanType = predictBeanType(beanName, mbd, FactoryBean.class);
return (beanType != null && FactoryBean.class.isAssignableFrom(beanType));
}
AbstractAutowireCapableBeanFactory.predictBeanType
、
AbstractAutowireCapableBeanFactory.determineTargetType
protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
// 确定目标类型
Class<?> targetType = determineTargetType(beanName, mbd, typesToMatch);
if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 如果有实现了SmartInstantiationAwareBeanPostProcessor的后置处理器
// 就通过后置处理器来预测最终的类型
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
// 通过后置处理器来预测最终的类型
Class<?> predicted = ibp.predictBeanType(targetType, beanName);
// 这里的逻辑?有点懵
if (predicted != null && (typesToMatch.length != 1 || !FactoryBean.class.equals(typesToMatch[0]) ||
FactoryBean.class.isAssignableFrom(predicted))) {
return predicted;
}
}
}
}
return targetType;
}
protected Class<?> determineTargetType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
// RootBeanDefinition中存储哪个类的信息
Class<?> targetType = mbd.getTargetType();
if (targetType == null) {
/**
* // 通过beanAFactory中的getBeanA方法来获取
* <bean id="beanA" factory-bean="beanAFactory" factory-method="getBeanA">
* </bean>
*/
// 如果bean有定义factory-method,从factoryMethod中获取类型
// 否则就从RootBeanDefinition中获取beanClass,下文解析,内部还包含通过classLoader加载class
targetType = (mbd.getFactoryMethodName() != null ? getTypeForFactoryMethod(beanName, mbd, typesToMatch) :
resolveBeanClass(mbd, beanName, typesToMatch));
if (ObjectUtils.isEmpty(typesToMatch) || getTempClassLoader() == null) {
// 设置RootBeanDefinition中存储哪个类的信息
mbd.setTargetType(targetType);
}
}
return targetType;
}
DefaultSingletonBeanRegistry.getSingleton
、
DefaultSingletonBeanRegistry.containsSingleton
、
DefaultSingletonBeanRegistry.beforeSingletonCreation
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// 获取这个bean
Object singletonObject = this.singletonObjects.get(beanName);
// 未获取到bean,而bean正在创建中时
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
// 从提前暴露的缓存中获取bean
singletonObject = this.earlySingletonObjects.get(beanName);
// 如果没有提前暴露 并且是允许提前引用(是否允许从singletonFactories中获取单例对象)
// 注:上述allowEarlyReference传入的是false,所以不会进这里,singletonFactories也为空
if (singletonObject == null && allowEarlyReference) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
// 从singletonFactory中获取单例对象
singletonObject = singletonFactory.getObject();
// 缓存在提前暴露的Map里(earlySingletonObjects)
this.earlySingletonObjects.put(beanName, singletonObject);
// 从singletonFactories中去除
this.singletonFactories.remove(beanName);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
public boolean containsSingleton(String beanName) {
return this.singletonObjects.containsKey(beanName);
}
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "'beanName' must not be null");
synchronized (this.singletonObjects) {
// 从缓存中取
Object singletonObject = this.singletonObjects.get(beanName);
// 如果缓存里没有
if (singletonObject == null) {
// 如果这个工厂处于销毁状态,就不用创建了,报错
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while the singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
// 在创建前,先判断bean是否为不能加载的bean 和 bean是否在创建中
beforeSingletonCreation(beanName);
// 标识这个单例还没被创建
boolean newSingleton = false;
// suppressedExceptions 存放所有异常的Set集合
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
// 异常集合为空就初始化
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<Exception>();
}
try {
// 这里才是执行创建bean的流程(createBean)
singletonObject = singletonFactory.getObject();
// 如果没有报异常 就标识创建成功
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
// 创建之后
afterSingletonCreation(beanName);
}
// 创建成功
if (newSingleton) {
// 三级缓存的操作
addSingleton(beanName, singletonObject);
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
}
protected void beforeSingletonCreation(String beanName) {
// 在创建前,
// 先判断bean是否为不能加载的bean
// &&
// 在正在创建的集合中添加beanName,添加成功,即:bean不在正在创建的集合中
// 单例bean构造器参数循环依赖,会直接报错
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
protected void afterSingletonCreation(String beanName) {
// 在创建后,
// 还是要判断bean是否为不能加载的bean
// &&
// 在正在创建的集合中移除beanName,移除成功,即:bean在正在创建的集合中
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
}
}
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
// 三级缓存的操作
// 将这个单例对象放入单例对象集合中
this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
// 从单例工厂集合中移除
this.singletonFactories.remove(beanName);
// 从提前暴露的单例对象集合中移除
this.earlySingletonObjects.remove(beanName);
// 将beanName放入已经注册过的单例对象名称集合中
this.registeredSingletons.add(beanName);
}
}
DefaultSingletonBeanRegistry.isSingletonCurrentlyInCreation
public boolean isSingletonCurrentlyInCreation(String beanName) {
return this.singletonsCurrentlyInCreation.contains(beanName);
}
AbstractBeanFactory.getBean
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
protected <T> T doGetBean(
final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
// 转化为真实beanName
final String beanName = transformedBeanName(name);
Object bean;
// 获取单例bean
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
// 这个bean类型可能是个FactoryBean
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// 翻译:如果我们已经在创建这个bean实例,则失败:我们可以在循环引用中进行组合。
// 从当前线程中获取正在创建的对象集合,判断beanName是否在这个集合里
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// 从parentBeanFactory中查找是否存在
BeanFactory parentBeanFactory = getParentBeanFactory();
// 存在parentBeanFactory 并且 当前BeanFactory中没有beanName对应的BeanDefinition
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// 无论name前面有多少个&,返回的beanName最多只有一个&
// 源码下文
String nameToLookup = originalBeanName(name);
if (args != null) {
// args有参数 => 使用显式参数委派到父级
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
// args没参数 => 使用标准getBean方法
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
// -----------------------进入开始创建的流程-----------------------
if (!typeCheckOnly) {
// 标记这个bean
// 源码
/*
protected void markBeanAsCreated(String beanName) {
if (!this.alreadyCreated.contains(beanName)) {
this.alreadyCreated.add(beanName);
}
}
*/
markBeanAsCreated(beanName);
}
try {
// 获取合并后的RootBeanDefinition
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 检查mdb是不是抽象类
// 源码
/*
protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, Object[] args)
throws BeanDefinitionStoreException {
if (mbd.isAbstract()) {
throw new BeanIsAbstractException(beanName);
}
}
*/
checkMergedBeanDefinition(mbd, beanName, args);
// 获取所有依赖的beanName
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dependsOnBean : dependsOn) {
if (isDependent(beanName, dependsOnBean)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
}
// bean和依赖bean,互相关联,源码下文
registerDependentBean(dependsOnBean, beanName);
// 递归调用getBean(),目的是为了在实例化当前bean之前,把依赖的bean先加载
getBean(dependsOnBean);
}
}
// 创建bean实例
// 单例的情况下
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
// 原型模式
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; " +
"consider defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type [" +
ClassUtils.getQualifiedName(requiredType) + "]", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
AbstractAutowireCapableBeanFactory.createBean
protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
// 通过classLoader加载beanClass
resolveBeanClass(mbd, beanName);
// 准备方法重写
try {
mbd.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// 让BeanPostProcessors有机会返回代理而不是目标bean实例
// Instantiation => 实例化
// Initialization => 初始化
// 顺序为
// 实例化之前 => 实例化之后 => 初始化之前 => 初始化之后
Object bean = resolveBeforeInstantiation(beanName, mbd);
// 如果已经被后置处理器实例化过,就直接返回,不需要经过下面的doCreateBean来实例化对象
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
// 实例化对象
Object beanInstance = doCreateBean(beanName, mbd, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
AbstractBeanFactory.hasBeanClass
AbstractBeanFactory.resolveBeanClass
public boolean hasBeanClass() {
return (this.beanClass instanceof Class);
}
protected Class<?> resolveBeanClass(final RootBeanDefinition mbd, String beanName, final Class<?>... typesToMatch)
throws CannotLoadBeanClassException {
try {
// 从mbd中直接获取bean的类型
// 有可能beanClass有值,但是beanClass instanceof Class为false,
// 因为在这个classLoader里并没有加载这个class
if (mbd.hasBeanClass()) {
return mbd.getBeanClass();
}
// 如果还没加载这个class,那就要通过ClassLoader来加载
// System.getSecurityManager()
// 如果在程序里开启了权限检查:System.setSecurityManager(new SecurityManager())
// 操作某些没有权限的文件时,会报错,所以要通过AccessController.doPrivileged,来执行
// 即:越权操作
if (System.getSecurityManager() != null) {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() {
@Override
public Class<?> run() throws Exception {
// 解析bean的类型
return doResolveBeanClass(mbd, typesToMatch);
}
}, getAccessControlContext());
}
else {
return doResolveBeanClass(mbd, typesToMatch);
}
}
catch (PrivilegedActionException pae) {
ClassNotFoundException ex = (ClassNotFoundException) pae.getException();
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
}
catch (ClassNotFoundException ex) {
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
}
catch (LinkageError err) {
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err);
}
}
private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch) throws ClassNotFoundException {
if (!ObjectUtils.isEmpty(typesToMatch)) {
ClassLoader tempClassLoader = getTempClassLoader();
if (tempClassLoader != null) {
// 如果tempClassLoader是DecoratingClassLoader类型,就把所有要匹配的类型(typesToMatch)添加到tempClassLoader
// DecoratingClassLoader的作用:使这些类不被自定义的classLoader管理,即:使用jdk默认加载机制
if (tempClassLoader instanceof DecoratingClassLoader) {
DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader;
for (Class<?> typeToMatch : typesToMatch) {
dcl.excludeClass(typeToMatch.getName());
}
}
String className = mbd.getBeanClassName();
return (className != null ? ClassUtils.forName(className, tempClassLoader) : null);
}
}
// 这里涉及到类加载
return mbd.resolveBeanClass(getBeanClassLoader());
}
AbstractBeanDefinition.resolveBeanClass
AbstractBeanDefinition.prepareMethodOverrides
public Class<?> resolveBeanClass(ClassLoader classLoader) throws ClassNotFoundException {
String className = getBeanClassName();
if (className == null) {
return null;
}
// 从classLoader中加载class
Class<?> resolvedClass = ClassUtils.forName(className, classLoader);
this.beanClass = resolvedClass;
return resolvedClass;
}
public void prepareMethodOverrides() throws BeanDefinitionValidationException {
// 获取methodOverrides
MethodOverrides methodOverrides = getMethodOverrides();
// 如果不为空,就准备重写
if (!methodOverrides.isEmpty()) {
for (MethodOverride mo : methodOverrides.getOverrides()) {
prepareMethodOverride(mo);
}
}
}
protected void prepareMethodOverride(MethodOverride mo) throws BeanDefinitionValidationException {
// 获取这个类中有几个方法名
int count = ClassUtils.getMethodCountForName(getBeanClass(), mo.getMethodName());
// 如果为0,说明没有方法可以重写
if (count == 0) {
throw new BeanDefinitionValidationException(
"Invalid method override: no method with name '" + mo.getMethodName() +
"' on class [" + getBeanClassName() + "]");
}
// 如果为1,设置标识为false,即表示还没有重写
else if (count == 1) {
// Mark override as not overloaded, to avoid the overhead of arg type checking.
mo.setOverloaded(false);
}
// 如果大于1,就不知道重写哪个方法了
}
AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
// 实例化之前判断是否已经被后置处理器实例化过
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// 如果还没实例化,就通过调用自定义的后置处理器来获取对象
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
// 调用自定义的beanPostProcessorsBeforeInstantiation实例化之前的处理
// 可以返回代理对象
// 如果在实例化之前调用自定义的后置处理器,有返回实例化对象的时候,就直接返回这个对象
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
// 如果获取到代理对象
// 则调用beanPostProcessorsAfterInitialization来操作初始化之后的处理
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
// 是否在实例化前被后置处理器实例化过
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
// 实例化前
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName)
throws BeansException {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 如果在实例化之前调用自定义的后置处理器,有返回实例化对象的时候,就直接返回这个对象
// 额..听起来比较拗口
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
// 初始化后的操作
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessAfterInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
// !!!!这里才是创建bean对象的实现!!!!
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
// 实例化bean
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
mbd.postProcessed = true;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
AbstractBeanFactory.isPrototypeCurrentlyInCreation
protected boolean isPrototypeCurrentlyInCreation(String beanName) {
// prototypesCurrentlyInCreation是ThreadLocal
// 从当前线程中获取正在创建的对象集合,判断beanName是否在这个集合里
Object curVal = this.prototypesCurrentlyInCreation.get();
return (curVal != null &&
(curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName))));
}
AbstractBeanFactory.getObjectForBeanInstance
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {
/*
if(a && b) {}
if(b || a) {}
如果A满足,B满足,再B满足
如果A满足,B不满足,再B不满足,A满足
如果A不满足,再B满足,
如果A不满足,再B不满足,A不满足
对比
if(a && b) {}
if(a || b) {}
如果A满足,B满足,再A满足
如果A满足,B不满足,再A满足
如果A不满足,再A不满足,B是否满足
他这个反着的写法优势在哪里???
*/
// 如果要获取的bean是FactoryBean对象(name是&开头),但是又没有实现FactoryBean,则报错
// public static boolean isFactoryDereference(String name) {
// return (name != null && name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX));
//}
if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
}
// 如果bean没有实现FactoryBean接口 或者 获取的bean是FactoryBean对象(name是&开头),直接返回,因为他并没有实现FactoryBean
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
return beanInstance;
}
Object object = null;
if (mbd == null) {
// 从缓存(factoryBeanObjectCache)里获取实例
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
// 如果缓存中没有,就从FactoryBean中获取,并缓存
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
if (mbd == null && containsBeanDefinition(beanName)) {
mbd = getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = (mbd != null && mbd.isSynthetic());
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
FactoryBeanRegistrySupport.getCachedObjectForFactoryBean
protected Object getCachedObjectForFactoryBean(String beanName) {
Object object = this.factoryBeanObjectCache.get(beanName);
return (object != NULL_OBJECT ? object : null);
}
FactoryBeanRegistrySupport.getObjectFromFactoryBean
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
// 如果FactoryBean是单例 并且 singletonObjects中包含这个bean
if (factory.isSingleton() && containsSingleton(beanName)) {
synchronized (getSingletonMutex()) {
// 从缓存中查找
Object object = this.factoryBeanObjectCache.get(beanName);
if (object == null) {
// 这里才是去FactoryBean里获取对象
object = doGetObjectFromFactoryBean(factory, beanName);
// 注释翻译:
// 在上面的getObject()调用中,只有在还没有放置的情况下才进行后期处理和存储(例如,由于自定义getBean调用触发了循环引用处理)
// 就是说,上面FactoryBean.getObject()里是自定义的,并不知道有没有缓存过,所以在这里再获取一遍,如果没有缓存过,那就进行缓存
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
object = alreadyThere;
}
else {
// 如果shouldPostProcess为true,就需要执行后置处理器(postProcessAfterInitialization)
// 源码下文
if (object != null && shouldPostProcess) {
try {
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Post-processing of FactoryBean's singleton object failed", ex);
}
}
// 放入缓存
this.factoryBeanObjectCache.put(beanName, (object != null ? object : NULL_OBJECT));
}
}
return (object != NULL_OBJECT ? object : null);
}
}
else {
// 不是单例就不用放到缓存,直接从FactoryBean中获取
Object object = doGetObjectFromFactoryBean(factory, beanName);
if (object != null && shouldPostProcess) {
try {
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
}
}
return object;
}
}
FactoryBeanRegistrySupport.doGetObjectFromFactoryBean
private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, final String beanName)
throws BeanCreationException {
Object object;
try {
if (System.getSecurityManager() != null) {
AccessControlContext acc = getAccessControlContext();
try {
object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
// 通过getObject()获取对象
return factory.getObject();
}
}, acc);
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
object = factory.getObject();
}
}
catch (FactoryBeanNotInitializedException ex) {
throw new BeanCurrentlyInCreationException(beanName, ex.toString());
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
}
// 如果bean还在创建中,就返回null
if (object == null && isSingletonCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(
beanName, "FactoryBean which is currently in creation returned null from getObject");
}
return object;
}
AbstractAutowireCapableBeanFactory.postProcessObjectFromFactoryBean
AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization
@Override
protected Object postProcessObjectFromFactoryBean(Object object, String beanName) {
return applyBeanPostProcessorsAfterInitialization(object, beanName);
}
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
// 每次执行完后置处理器,就返回修改后的结果,如果把bean设置为null,那也就直接返回null
result = beanProcessor.postProcessAfterInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
DefaultSingletonBeanRegistry.registerDependentBean
public void registerDependentBean(String beanName, String dependentBeanName) {
// 获取真实beanName
String canonicalName = canonicalName(beanName);
// key => beanName
// value => beanName依赖的dependentBeanName的集合
Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
// 如果依赖的dependentBeanName已经在这个集合里了,就结束
if (dependentBeans != null && dependentBeans.contains(dependentBeanName)) {
return;
}
// 如果没有在集合里
// key => beanName
// value => beanName依赖的dependentBeanName的集合
synchronized (this.dependentBeanMap) {
dependentBeans = this.dependentBeanMap.get(canonicalName);
// 集合为null,先初始化集合
if (dependentBeans == null) {
dependentBeans = new LinkedHashSet<String>(8);
this.dependentBeanMap.put(canonicalName, dependentBeans);
}
// 把依赖的dependentBeanName对应起来
dependentBeans.add(dependentBeanName);
}
// key => dependentBeanName
// value => 所有依赖dependentBeanName的beanName(真实beanName)集合
// 与上面这个相反:
// 上面这个是beanName对应所有依赖beanName
// 下面这个是依赖beanName对应所有beanName
synchronized (this.dependenciesForBeanMap) {
Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName);
if (dependenciesForBean == null) {
dependenciesForBean = new LinkedHashSet<String>(8);
this.dependenciesForBeanMap.put(dependentBeanName, dependenciesForBean);
}
dependenciesForBean.add(canonicalName);
}
}
BeanFactory与FactoryBean的区别
AbstractBeanFactory类中的部分方法
protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
// 根据bean名字获取合并过的beanDefinition
RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
// 如果已经合并过,直接返回合并后的
if (mbd != null) {
return mbd;
}
// 合并beanDefinition
return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}
protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
throws BeanDefinitionStoreException {
return getMergedBeanDefinition(beanName, bd, null);
}
protected RootBeanDefinition getMergedBeanDefinition(
String beanName, BeanDefinition bd, BeanDefinition containingBd)
throws BeanDefinitionStoreException {
// 加锁进行合并操作
synchronized (this.mergedBeanDefinitions) {
RootBeanDefinition mbd = null;
// Check with full lock now in order to enforce the same merged instance.
if (containingBd == null) {
mbd = this.mergedBeanDefinitions.get(beanName);
}
if (mbd == null) {
// 如果没有父类,即没有配置parent
if (bd.getParentName() == null) {
// BeanDefinition转成RootBeanDefinition
if (bd instanceof RootBeanDefinition) {
mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
}
else {
mbd = new RootBeanDefinition(bd);
}
}
else {
// 要将子类合并到父类
BeanDefinition pbd;
try {
// transformedBeanName的目的是获取bean的真实名字,这里获取的是bean的parent name,详情见下文
String parentBeanName = transformedBeanName(bd.getParentName());
// bean name 和 parent name不同时,递归合并parent, parent.parent。。。。
if (!beanName.equals(parentBeanName)) {
pbd = getMergedBeanDefinition(parentBeanName);
}
else {
// 疑问:我好像没发现有parentBeanFactory??
if (getParentBeanFactory() instanceof ConfigurableBeanFactory) {
pbd = ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(parentBeanName);
}
else {
throw new NoSuchBeanDefinitionException(bd.getParentName(),
"Parent name '" + bd.getParentName() + "' is equal to bean name '" + beanName +
"': cannot be resolved without an AbstractBeanFactory parent");
}
}
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
}
// 将parentBeanDefinition作为RootBeanDefinition,把属性深度覆盖
mbd = new RootBeanDefinition(pbd);
// 覆盖属性的方法,源码没列出来
mbd.overrideFrom(bd);
}
// 默认为单例bean
if (!StringUtils.hasLength(mbd.getScope())) {
mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);
}
if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
mbd.setScope(containingBd.getScope());
}
if (containingBd == null && isCacheBeanMetadata() && isBeanEligibleForMetadataCaching(beanName)) {
this.mergedBeanDefinitions.put(beanName, mbd);
}
}
return mbd;
}
}
protected String transformedBeanName(String name) {
return canonicalName(BeanFactoryUtils.transformedBeanName(name));
}
// BeanFactoryUtils.transformedBeanName的源码
public static String transformedBeanName(String name) {
Assert.notNull(name, "'name' must not be null");
String beanName = name;
// 判断bean是否为"&"开头
while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
}
// 返回去除&的名字,而这个名字不一定是真实的bean name,有可能是别名
return beanName;
}
// SimpleAliasRegistry.canonicalName的源码
// 获取真实的beanName
public String canonicalName(String name) {
String canonicalName = name;
String resolvedName;
// 无限取,直到取到真实的bean name,
// 可能a的别名是b,b的别名是c
do {
resolvedName = this.aliasMap.get(canonicalName);
if (resolvedName != null) {
canonicalName = resolvedName;
}
}
while (resolvedName != null);
// 直到别名map中没有对应的值时,才返回这个bean name(真实的bean name)
return canonicalName;
}
// 无论name前面有多少个&,返回的beanName最多只有一个&
protected String originalBeanName(String name) {
String beanName = transformedBeanName(name);
if (name.startsWith(FACTORY_BEAN_PREFIX)) {
beanName = FACTORY_BEAN_PREFIX + beanName;
}
return beanName;
}
等待后文 (上次更新时间:2019/12/11)- line 1614
...
...
...
...
...
...
...
...
...
...
...
...
...
等待后文...