- 使用 Spring Initializr 创建 Spring Boot 应用程序
- 在Spring Boot中配置Cassandra
- 在 Spring Boot 上配置 Tomcat 连接池
- 将Camel消息路由到嵌入WildFly的Artemis上
上一篇解析了上下文组件(WebApplicationContext),但留下一些点待解析:
ConfigurableListableBeanFactory
如何加载、实例化 beanResourceEditorRegistrar
如何注册属性编辑器、属性编辑器如何解析为对象PathMatchingResourcePatternResolver
如何解析、加载 locationPattern 指定的资源PropertySourcesPropertyResolver
如何是解析路径的XmlBeanDefinitionReader
如何是解析 bean 定义的AnnotatedBeanDefinitionReader
是如何注册 bean 的ClassPathBeanDefinitionScanner
是如何扫描包的Bean 的注册、解析、实例化主要是 ConfigurableListableBeanFactory 完成的,但ConfigurableListableBeanFactory
只是一个接口,DefaultListableBeanFactory 是其默认实现
先来看看 DefaultListableBeanFactory
的继承关系
- SimpleAliasRegistry
- DefaultSingletonBeanRegistry
- FactoryBeanRegistrySupport
- AbstractBeanFactory
- AbstractAutowireCapableBeanFactory
- DefaultListableBeanFactory
SimpleAliasRegistry
简单的 bean 别名管理器
public class SimpleAliasRegistry implements AliasRegistry {}
先来看看接口AliasRegistry
public interface AliasRegistry {
// 注册bean别名
void registerAlias(String name, String alias);
// 移除bean别名
void removeAlias(String alias);
// 检查是否是bean别名
boolean isAlias(String name);
// 获取bean别名
String[] getAliases(String name);
}
SimpleAliasRegistry
是 AliasRegistry
的简单实现
public class SimpleAliasRegistry implements AliasRegistry {
// 别名容器,使用ConcurrentHashMap实现
private final Map<String, String> aliasMap = new ConcurrentHashMap<>(16);
@Override
public void registerAlias(String name, String alias) {
synchronized (this.aliasMap) {
if (alias.equals(name)) {
// 如果名字与别名相同,则删除别名
this.aliasMap.remove(alias);
}
else {
// 载入别名
this.aliasMap.put(alias, name);
}
}
}
@Override
public void removeAlias(String alias) {
synchronized (this.aliasMap) {
String name = this.aliasMap.remove(alias);
}
}
@Override
public boolean isAlias(String name) {
return this.aliasMap.containsKey(name);
}
@Override
public String[] getAliases(String name) {
List<String> result = new ArrayList<>();
synchronized (this.aliasMap) {
// 根据名字反向找别名
retrieveAliases(name, result);
}
return StringUtils.toStringArray(result);
}
}
DefaultSingletonBeanRegistry
默认的单例管理器
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {}
先来看看接口SingletonBeanRegistry
public interface SingletonBeanRegistry {
// 注册单例bean
void registerSingleton(String beanName, Object singletonObject);
// 获取单例bean
Object getSingleton(String beanName);
}
DefaultSingletonBeanRegistry
是 SingletonBeanRegistry
的默认实现
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
// 单例对象Map: bean name => bean instance
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
// 单例生成工厂Map: bean name => ObjectFactory
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
// 单例对象Map: bean name => bean instance(解决循环依赖)
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
// 已注册单例对象bean name集合
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
// 可销毁单例对象Map: bean name => bean instance
private final Map<String, Object> disposableBeans = new LinkedHashMap<>();
// 单例对象拥有内部单例集合Map: bean name => bean instance set(比如class是一个bean,class内部的方法也是一个bean)
private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<>(16);
// 单例对象的被依赖集合Map: bean name => bean instance set(其他bean依赖这个bean)
private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64);
// 单例对象的依赖集合Map: bean name => bean instance set
private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<>(64);
}
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
// 注入单例对象,如果已存在,则报错
@Override
public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
synchronized (this.singletonObjects) {
Object oldObject = this.singletonObjects.get(beanName);
if (oldObject != null) {
throw new IllegalStateException("Could not register object [" + singletonObject +
"] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
}
addSingleton(beanName, singletonObject);
}
}
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
// 注入,临时和定义都去掉
this.singletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
}
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
// 获取单例
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// 先尝试从singletonObjects中获取
Object singletonObject = this.singletonObjects.get(beanName);
// 如果没有,单例已经在创建中,还没有完成
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
// 从早期集合中找(可能依赖没有完成)
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
// 如果仍然没有,锁住singletonObjects对象,从singletonFactories中创建
synchronized (this.singletonObjects) {
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
// 从创建工厂创建单例对象
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
}
}
return singletonObject;
}
// 获取单例,如果不存在,就用singletonFactory创建一个新的
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
boolean newSingleton = false;
try {
// ... 代码省略
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// ... 代码省略
}
catch (BeanCreationException ex) {
// ... 代码省略
}
finally {
// ... 代码省略
}
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
}
FactoryBeanRegistrySupport
的主要功能是实现对 FactoryBean
的支持
先来看看接口 FactoryBean
有哪些方法
public interface FactoryBean<T> {
// 获取对象实例
T getObject() throws Exception;
// 获取对象类型
Class<?> getObjectType();
}
与 DefaultSingletonBeanRegistry
中的对象生成接口 ObjectFactory
不同的是,FactoryBean
多了一个 getObjectType
用来获取对象类型,这样就可以不用实例化也可以知道 bean 的类型,这对诸如 autowiring 自动装配对象这类功能非常有用
来看看 FactoryBeanRegistrySupport
的具体实现
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
// FactoryBeans实例缓存: FactoryBean name => object
private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>(16);
// 获取factoryBean所代表的bean的类型
protected Class<?> getTypeForFactoryBean(FactoryBean<?> factoryBean) {
try {
// 如果有JVM安全检查,绕过
if (System.getSecurityManager() != null) {
return AccessController.doPrivileged(
(PrivilegedAction<Class<?>>) factoryBean::getObjectType, getAccessControlContext());
}
else {
return factoryBean.getObjectType();
}
}
catch (Throwable ex) {
// ... 代码省略
}
}
// 获取factoryBean所代表的bean的实例
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
// 如果是单例,并且已经创建过
if (factory.isSingleton() && containsSingleton(beanName)) {
// 锁住父类的singletonObjects
synchronized (getSingletonMutex()) {
Object object = this.factoryBeanObjectCache.get(beanName);
if (object == null) {
// 创建实例
object = doGetObjectFromFactoryBean(factory, beanName);
// 并发处理,有其他线程创建了,就舍弃自己创建的
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
object = alreadyThere;
}
else {
if (shouldPostProcess) {
// ... 代码省略
try {
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
// ... 代码省略
}
finally {
// ... 代码省略
}
}
if (containsSingleton(beanName)) {
this.factoryBeanObjectCache.put(beanName, object);
}
}
}
return object;
}
}
else {
// 如果非单例,或者单例未创建过,直接创建
Object object = doGetObjectFromFactoryBean(factory, beanName);
if (shouldPostProcess) {
try {
// 后置处理
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
// ... 代码省略
}
}
return object;
}
}
// 创建bean
private Object doGetObjectFromFactoryBean(FactoryBean<?> factory, String beanName) throws BeanCreationException {
Object object;
try {
// 如果有JVM安全检查,绕过
if (System.getSecurityManager() != null) {
AccessControlContext acc = getAccessControlContext();
try {
object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
}
catch (PrivilegedActionException pae) {
// ... 代码省略
}
}
else {
object = factory.getObject();
}
}
catch (FactoryBeanNotInitializedException ex) {
// ... 代码省略
}
catch (Throwable ex) {
// ... 代码省略
}
// 如果创建的实例是null,则返回一个NullBean实例
if (object == null) {
if (isSingletonCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(
beanName, "FactoryBean which is currently in creation returned null from getObject");
}
object = new NullBean();
}
return object;
}
// 扩展子类后置处理
protected Object postProcessObjectFromFactoryBean(Object object, String beanName) throws BeansException {
return object;
}
}
AbstractBeanFactory
是 bean 管理的核心类,主要有以下几个方法
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
@Override
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return doGetBean(name, requiredType, null, false);
}
@Override
public Object getBean(String name, Object... args) throws BeansException {
return doGetBean(name, null, args, false);
}
public <T> T getBean(String name, @Nullable Class<T> requiredType, @Nullable Object... args)
throws BeansException {
return doGetBean(name, requiredType, args, false);
}
protected <T> T doGetBean(
String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {
// 获取真实的bean名称,比如别名、&开头的FactoryBean等
String beanName = transformedBeanName(name);
Object beanInstance;
// 先获取单例
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
// 如果是FactoryBean实例,则获取其包含的bean实例,否则就是自身
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
try {
// 如果有父bean(比如class是一个bean,class内部的方法也是一个bean),则合并父bean的定义
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 获取依赖
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
// 记录依赖
registerDependentBean(dep, beanName);
try {
// 保证依赖bean已经实例化
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
// 如果不能实例化,抛出错误
}
}
}
// 单例bean
if (mbd.isSingleton()) {
// 获取单例bean,如果没有,就创建一个
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// 如果不能实例化,抛出错误
}
});
// 如果是FactoryBean实例,则获取其包含的bean实例,否则就是自身
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
// 原型bean
else if (mbd.isPrototype()) {
// 每次获取都重新实例化一个新的
Object prototypeInstance = null;
try {
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
// ... 代码省略
}
// 如果是FactoryBean实例,则获取其包含的bean实例,否则就是自身
beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
// 否则默认每次实例化一个新的,从scope中获取beanName
else {
String scopeName = mbd.getScope();
Scope scope = this.scopes.get(scopeName);
try {
Object scopedInstance = scope.get(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
finally {
// ... 代码省略
}
});
// 如果是FactoryBean实例,则获取其包含的bean实例,否则就是自身
beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
// ... 代码省略
}
}
}
catch (BeansException ex) {
// ... 代码省略
}
finally {
// ... 代码省略
}
}
// 最后再根据requiredType转换bean实例类型
return adaptBeanInstance(name, beanInstance, requiredType);
}
// 创建实例,留给子类实现
protected abstract Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException;
}
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
@Override
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
return getType(name, true);
}
@Override
public Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException {
// 获取真实的bean名称,比如别名、&开头的FactoryBean等
String beanName = transformedBeanName(name);
// 先尝试获取单例
Object beanInstance = getSingleton(beanName, false);
if (beanInstance != null && beanInstance.getClass() != NullBean.class) {
// 如果bean是FactoryBean定义的,并name不是&开头的(指包含的实际bean),则获取包含的实际bean类型
if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
return getTypeForFactoryBean((FactoryBean<?>) beanInstance);
}
// 否则获取单例本身
else {
return beanInstance.getClass();
}
}
// 没有单例对象,则检查是否有定义
BeanFactory parentBeanFactory = getParentBeanFactory();
// 如果当前beanFactory没有定义,但有父beanFactory,则在父beanFactory里查找
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
return parentBeanFactory.getType(originalBeanName(name));
}
// 合并父bean定义
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 如果是用装饰器模式定义的bean,则从装饰定义里查找
BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {
RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd);
if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
return targetClass;
}
}
// 从定义中找
Class<?> beanClass = predictBeanType(beanName, mbd);
// 如果bean是FactoryBean定义的
if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) {
if (!BeanFactoryUtils.isFactoryDereference(name)) {
// name不是&开头的(指包含的实际bean),则返回包含的实际bean类型
return getTypeForFactoryBean(beanName, mbd, allowFactoryBeanInit).resolve();
}
else {
// 否则返回beanClass本身
return beanClass;
}
}
// 否则返回beanClass本身
else {
return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null);
}
}
// 获取FactoryBean包含的实际bean类型
protected ResolvableType getTypeForFactoryBean(String beanName, RootBeanDefinition mbd, boolean allowInit) {
// 获取定义中的factoryBeanObjectType属性
ResolvableType result = getTypeForFactoryBeanFromAttributes(mbd);
// 如果不为空类型的话,返回
if (result != ResolvableType.NONE) {
return result;
}
// 如果是单例,或者非单例但可以初始化
if (allowInit && mbd.isSingleton()) {
try {
// 获取包含这个bean的factoryBean
FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
Class<?> objectType = getTypeForFactoryBean(factoryBean);
return (objectType != null ? ResolvableType.forClass(objectType) : ResolvableType.NONE);
}
catch (BeanCreationException ex) {
// ... 代码省略
}
}
return ResolvableType.NONE;
}
// 获取FactoryBean包含的实际bean类型
protected Class<?> getTypeForFactoryBean(FactoryBean<?> factoryBean) {
try {
if (System.getSecurityManager() != null) {
// 如果有JVM安全检查,绕过
return AccessController.doPrivileged(
(PrivilegedAction<Class<?>>) factoryBean::getObjectType, getAccessControlContext());
}
else {
// 直接调用getObjectType方法
return factoryBean.getObjectType();
}
}
catch (Throwable ex) {
return null;
}
}
// 根据定义查找bean类型
protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
Class<?> targetType = mbd.getTargetType();
// 指定targetType,则返回targetType
if (targetType != null) {
return targetType;
}
// 指定了factory-method属性,如
// <bean id="staticBean" class="com.example.springFactoryMethod.StaticFactory" factory-method="getStaticBean"></bean>
// 则返回null
if (mbd.getFactoryMethodName() != null) {
return null;
}
return resolveBeanClass(mbd, beanName, typesToMatch);
}
// 解析bean类型
protected Class<?> resolveBeanClass(RootBeanDefinition mbd, String beanName, Class<?>... typesToMatch)
throws CannotLoadBeanClassException {
try {
// 指定beanClass且是Class,则返回beanClass
if (mbd.hasBeanClass()) {
return mbd.getBeanClass();
}
if (System.getSecurityManager() != null) {
return AccessController.doPrivileged((PrivilegedExceptionAction<Class<?>>)
() -> doResolveBeanClass(mbd, typesToMatch), getAccessControlContext());
}
else {
return doResolveBeanClass(mbd, typesToMatch);
}
}
catch (PrivilegedActionException pae) {
// ... 代码省略
}
}
// 解析bean类型
private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch)
throws ClassNotFoundException {
ClassLoader beanClassLoader = getBeanClassLoader();
ClassLoader dynamicLoader = beanClassLoader;
boolean freshResolve = false;
// ... 代码省略
// 指定beanClass但是String
String className = mbd.getBeanClassName();
if (className != null) {
// 把beanClass从String解析成对象
Object evaluated = evaluateBeanDefinitionString(className, mbd);
if (!className.equals(evaluated)) {
// 如果是Class,直接返回
if (evaluated instanceof Class) {
return (Class<?>) evaluated;
}
// 如果仍是String,则用ClassLoader来加载
else if (evaluated instanceof String) {
className = (String) evaluated;
freshResolve = true;
}
else {
// 其他对象则报错
}
}
if (freshResolve) {
// ... 代码省略
return dynamicLoader.loadClass(className);
}
}
// 如果都没有,就用哪个ClassLoader来解析
return mbd.resolveBeanClass(beanClassLoader);
}
}
AbstractAutowireCapableBeanFactory
的主要功能是为 bean autowiring 自动装配依赖的 bean 对象
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {}
先来看看接口 AutowireCapableBeanFactory
的主要方法
public interface AutowireCapableBeanFactory {
// 根据beanClass创建bean实例
<T> T createBean(Class<T> beanClass) throws BeansException;
Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;
// 给existingBean装配依赖的其他bean实例
void autowireBean(Object existingBean) throws BeansException;
// 通过bean定义给existingBean装配属性
Object configureBean(Object existingBean, String beanName) throws BeansException;
// 根据beanClass创建并装配bean实例
Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;
}
再来看看 AbstractAutowireCapableBeanFactory
是如何实现的
AbstractAutowireCapableBeanFactory.createBean
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
@Override
public <T> T createBean(Class<T> beanClass) throws BeansException {
// 创建bean定义对象,设置为原型bean
RootBeanDefinition bd = new RootBeanDefinition(beanClass);
bd.setScope(SCOPE_PROTOTYPE);
bd.allowCaching = ClassUtils.isCacheSafe(beanClass, getBeanClassLoader());
return (T) createBean(beanClass.getName(), bd, null);
}
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
RootBeanDefinition mbdToUse = mbd;
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
// bean对应的类是存在的,但给出的是String类型的,不是Class类型的,则需要创建bean定义对象
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// ... 代码省略
try {
// 做一些前置初始化,如果其中实例化了bean,则返回
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
// ... 代码省略
}
try {
// 创建bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
// ... 代码省略
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// ... 代码省略
}
catch (Throwable ex) {
// ... 代码省略
}
}
}
这其中有两个地方可以实例化 bean
先来看看 AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// 非自处理工具类bean,并且有BeanPostProcessor
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
// 获取targetType
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
// 初始化前置处理
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
// 初始化后置处理
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
// 获取targetType
protected Class<?> determineTargetType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
Class<?> targetType = mbd.getTargetType();
if (targetType == null) {
// 如果指定了factory-method属性,则调用getTypeForFactoryMethod处理
// 否则直接解析beanClass
targetType = (mbd.getFactoryMethodName() != null ?
getTypeForFactoryMethod(beanName, mbd, typesToMatch) :
resolveBeanClass(mbd, beanName, typesToMatch));
// ... 代码省略
}
return targetType;
}
// 应用InstantiationAwareBeanPostProcessors到beanClass上
// 并调用他们的postProcessBeforeInstantiation做初始化前置处理
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
Object result = bp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
return null;
}
// 应用BeanPostProcessors到bean实例上,并调用他们的postProcessAfterInitialization做初始化后置处理
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
}
上面有一个方法没有解析,AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod
,内容较多,有兴趣可以自行探索
再来看看 AbstractAutowireCapableBeanFactory.doCreateBean
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// 实例化的bean会用BeanWrapper包裹
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// 如果是单例,先尝试从factoryBeanInstanceCache中获取
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 没有,则创建
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// 获取instanceWrapper包裹的bean实例
Object bean = instanceWrapper.getWrappedInstance();
// 获取instanceWrapper包裹的bean类型
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// ... 代码省略
Object exposedObject = bean;
try {
// 装载依赖的bean
populateBean(beanName, mbd, instanceWrapper);
// 对bean实例进行一些初始化操作,包括工厂回调、后置处理
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
// ... 代码省略
}
// ... 代码省略
return exposedObject;
}
// 创建bean实例
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// 解析Class
Class<?> beanClass = resolveBeanClass(mbd, beanName);
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
// 如果BeanDefinition有自定义Supplier,则调用Supplier.get
return obtainFromSupplier(instanceSupplier, beanName);
}
if (mbd.getFactoryMethodName() != null) {
// 如果指定了factory-method属性,则调用ConstructorResolver.instantiateUsingFactoryMethod处理
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
// 需要通过构造方法装配bean
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
// 通过构造方法装配bean
return autowireConstructor(beanName, mbd, null, null);
}
else {
// 不通过构造方法装配bean
return instantiateBean(beanName, mbd);
}
}
// 从BeanPostProcessors中选取构造方法
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
// 通过构造方法装配bean
return autowireConstructor(beanName, mbd, ctors, args);
}
// 选择构造方法
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
// 通过构造方法装配bean
return autowireConstructor(beanName, mbd, ctors, null);
}
// 默认不通过构造方法装配bean
return instantiateBean(beanName, mbd);
}
// 使用ConstructorResolver.autowireConstructor来实例化
protected BeanWrapper autowireConstructor(
String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) {
return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
}
// 不通过构造方法装配bean
protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
try {
Object beanInstance;
if (System.getSecurityManager() != null) {
// 如果有JVM安全检查,绕过
beanInstance = AccessController.doPrivileged(
(PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
getAccessControlContext());
}
else {
// 默认使用CglibSubclassingInstantiationStrategy.instantiate来实例化
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
}
// 用BeanWrapper包裹bean实例
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
// ... 代码省略
}
}
// 对bean实例进行一些初始化操作,包括工厂回调、后置处理
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
// ... 代码省略
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 调用BeanPostProcessors的postProcessBeforeInitialization做初始化前后置处理
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 调用bean初始化后的钩子方法,如果是InitializingBean,调用afterPropertiesSet方法
// 如果有设置initMethodName,也会调用
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
// ... 代码省略
}
if (mbd == null || !mbd.isSynthetic()) {
// 调用BeanPostProcessors的postProcessAfterInitialization做初始化后后置处理
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
}
ConstructorResolver.autowireConstructor
和CglibSubclassingInstantiationStrategy.instantiate
待解析AbstractAutowireCapableBeanFactory.autowireBean
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
@Override
public void autowireBean(Object existingBean) {
// 先找出existingBean的定义对象
RootBeanDefinition bd = new RootBeanDefinition(ClassUtils.getUserClass(existingBean));
bd.setScope(SCOPE_PROTOTYPE);
bd.allowCaching = ClassUtils.isCacheSafe(bd.getBeanClass(), getBeanClassLoader());
// 用BeanWrapper包裹
BeanWrapper bw = new BeanWrapperImpl(existingBean);
// 初始化
initBeanWrapper(bw);
// 装载依赖的bean
populateBean(bd.getBeanClass().getName(), bd, bw);
}
// 装载依赖的bean
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
// 获取bean的属性值集合
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
// 按名字或类型装配
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// 按名字装配
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// 按类型装配
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
// 检查所有待装配的属性bean是否都已准备好
checkDependencies(beanName, mbd, filteredPds, pvs);
}
if (pvs != null) {
// 把依赖的bean装配的对象里
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
// 按名字装配
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
//获取需要且可以装配的属性名
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
// 如果propertyName对应的bean已经实例化
if (containsBean(propertyName)) {
Object bean = getBean(propertyName);
// 把bean载入pvs
pvs.add(propertyName, bean);
// 记录依赖
registerDependentBean(propertyName, beanName);
}
}
}
// 按类型装配
protected void autowireByType(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
// 自定义类型转换器,如果没有,默认使用bw
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
//获取需要且可以装配的属性名
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
try {
// 获取属性描述器
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
// Object不可装配,因为没有意义,其他Class都可装配
if (Object.class != pd.getPropertyType()) {
// 获取可写属性
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// 确定是否有@Order注解,后置处理需要按顺序来处理
boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
// 解析propertyName的参数依赖
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
if (autowiredArgument != null) {
// 把bean载入pvs
pvs.add(propertyName, autowiredArgument);
}
for (String autowiredBeanName : autowiredBeanNames) {
// 记录依赖
registerDependentBean(autowiredBeanName, beanName);
}
autowiredBeanNames.clear();
}
}
catch (BeansException ex) {
// ... 代码省略
}
}
}
// 把依赖的bean装配到对象里
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
MutablePropertyValues mpvs = null;
// 原始值,待深拷贝(载入的对象都是深拷贝的)
List<PropertyValue> original;
if (pvs instanceof MutablePropertyValues) {
mpvs = (MutablePropertyValues) pvs;
// ... 代码省略
original = mpvs.getPropertyValueList();
}
else {
original = Arrays.asList(pvs.getPropertyValues());
}
// 自定义类型转换器
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
// bean解析器,对不同类型originalValue进行解析,如BeanDefinition、RuntimeBeanReference、ManagedList等
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
// 深拷贝的bean
List<PropertyValue> deepCopy = new ArrayList<>(original.size());
// 对每个原始值进行处理
for (PropertyValue pv : original) {
// ... 代码省略
// 属性名
String propertyName = pv.getName();
// 原始属性值
Object originalValue = pv.getValue();
// ... 代码省略
// 对originalValue进行解析
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
Object convertedValue = resolvedValue;
// ... 代码省略
// 如果originalValue已经是解析好的PropertyValue,则直接添加
if (resolvedValue == originalValue) {
// ... 代码省略
deepCopy.add(pv);
}
// ... 代码省略
// 不然就用PropertyValue包裹后再添加
else {
// ... 代码省略
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
// ... 代码省略
// 装配属性
try {
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
catch (BeansException ex) {
// ... 代码省略
}
}
}
这一小节留下 1 个点BeanDefinitionValueResolver.resolveValueIfNecessary
待解析
AbstractAutowireCapableBeanFactory.configureBean
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
@Override
public Object configureBean(Object existingBean, String beanName) throws BeansException {
// 合并父bean定义
BeanDefinition mbd = getMergedBeanDefinition(beanName);
// 获取封装得RootBeanDefinition
RootBeanDefinition bd = null;
if (mbd instanceof RootBeanDefinition) {
RootBeanDefinition rbd = (RootBeanDefinition) mbd;
bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition());
}
if (bd == null) {
bd = new RootBeanDefinition(mbd);
}
// 用BeanWrapper包裹bean实例
BeanWrapper bw = new BeanWrapperImpl(existingBean);
// 初始化
initBeanWrapper(bw);
// 装载依赖的bean
populateBean(beanName, bd, bw);
// 对bean实例进行一些初始化操作,包括工厂回调、后置处理
return initializeBean(beanName, existingBean, bd);
}
}
AbstractAutowireCapableBeanFactory.autowire
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
@Override
public Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException {
// 创建RootBeanDefinition
RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
// 默认的prototype
bd.setScope(SCOPE_PROTOTYPE);
// 通过构造方法装配bean
if (bd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR) {
return autowireConstructor(beanClass.getName(), bd, null, null).getWrappedInstance();
}
// 不通过构造方法装配bean
else {
Object bean;
if (System.getSecurityManager() != null) {
// 如果有JVM安全检查,绕过
bean = AccessController.doPrivileged(
(PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(bd, null, this),
getAccessControlContext());
}
else {
// 默认使用CglibSubclassingInstantiationStrategy.instantiate来实例化
bean = getInstantiationStrategy().instantiate(bd, null, this);
}
// 装载依赖的bean
populateBean(beanClass.getName(), bd, new BeanWrapperImpl(bean));
return bean;
}
}
}
DefaultListableBeanFactory
的主要功能是可以获取 bean 的列表数据,比如根据类型获取 bean 列表、根据注解获取 bean 列表等
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {}
先来看看接口 ConfigurableListableBeanFactory
的主要方法
public interface ConfigurableListableBeanFactory {
// 获取定义的bean名字集合
String[] getBeanDefinitionNames();
// 获取指定类型的bean实例名字集合
String[] getBeanNamesForType(ResolvableType type);
String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit);
String[] getBeanNamesForType(@Nullable Class<?> type);
String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit);
// 获取指定类型的bean实例Map,如果有bean没有被创建,会抛出错误
<T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException;
<T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException;
// 在指定的bean上找指定的注解
<A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
throws NoSuchBeanDefinitionException;
// 获取指定注解的bean实例名字集合
String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType);
// 获取指定注解的bean实例Map,如果有bean没有被创建,会抛出错误
Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException;
// 获取beanProvider,以使用懒加载
<T> ObjectProvider<T> getBeanProvider(Class<T> requiredType, boolean allowEagerInit);
<T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType, boolean allowEagerInit);
}
再来看看 DefaultListableBeanFactory
是如何实现的
DefaultListableBeanFactory.getBeanDefinitionNames
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
// bean定义Map,name => BeanDefinition
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
// bean定义容器(包含定义、别名、占位符${}解析等)Map,name => BeanDefinitionHolder
private final Map<String, BeanDefinitionHolder> mergedBeanDefinitionHolders = new ConcurrentHashMap<>(256);
// bean类型映射名字Map,type => name array
/** Map of singleton and non-singleton bean names, keyed by dependency type. */
private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64);
// 单例bean类型映射名字Map,type => name array
private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64);
// bean定义名字集合
private volatile List<String> beanDefinitionNames = new ArrayList<>(256);
// 单例bean名字集合
private volatile Set<String> manualSingletonNames = new LinkedHashSet<>(16);
// 固化(不再改变)bean定义名字集合
private volatile String[] frozenBeanDefinitionNames;
@Override
public String[] getBeanDefinitionNames() {
// 优先使用frozenBeanDefinitionNames,其次beanDefinitionNames
String[] frozenNames = this.frozenBeanDefinitionNames;
if (frozenNames != null) {
return frozenNames.clone();
}
else {
return StringUtils.toStringArray(this.beanDefinitionNames);
}
}
}
DefaultListableBeanFactory.getBeanNamesForType
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
@Override
public String[] getBeanNamesForType(ResolvableType type) {
return getBeanNamesForType(type, true, true);
}
@Override
public String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
Class<?> resolved = type.resolve();
if (resolved != null && !type.hasGenerics()) {
return getBeanNamesForType(resolved, includeNonSingletons, allowEagerInit);
}
else {
return doGetBeanNamesForType(type, includeNonSingletons, allowEagerInit);
}
}
@Override
public String[] getBeanNamesForType(@Nullable Class<?> type) {
return getBeanNamesForType(type, true, true);
}
@Override
public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
if (!isConfigurationFrozen() || type == null || !allowEagerInit) {
return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit);
}
// 先从缓存中获取,如果有缓存,直接返回
Map<Class<?>, String[]> cache =
(includeNonSingletons ? this.allBeanNamesByType : this.singletonBeanNamesByType);
String[] resolvedBeanNames = cache.get(type);
if (resolvedBeanNames != null) {
return resolvedBeanNames;
}
// 获取,并加入到缓存
resolvedBeanNames = doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, true);
if (ClassUtils.isCacheSafe(type, getBeanClassLoader())) {
cache.put(type, resolvedBeanNames);
}
return resolvedBeanNames;
}
}
这里的核心是 doGetBeanNamesForType
方法
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
List<String> result = new ArrayList<>();
// 检查所有的定义
for (String beanName : this.beanDefinitionNames) {
// 非别名才检查
if (!isAlias(beanName)) {
try {
// 获取合并父bean定义的RootBeanDefinition
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// ... 代码省略
// 判断FactoryBean
boolean isFactoryBean = isFactoryBean(beanName, mbd);
BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
boolean matchFound = false;
// ... 代码省略
// 普通bean
if (!isFactoryBean) {
if (includeNonSingletons || isSingleton(beanName, mbd, dbd)) {
// 检查是否与类型匹配
matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
}
}
else {
// FactoryBean需要特殊处理
if (includeNonSingletons || isNonLazyDecorated ||
(allowFactoryBeanInit && isSingleton(beanName, mbd, dbd))) {
// 检查是否与类型匹配
matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
}
if (!matchFound) {
// 如果不匹配,尝试 &beanName 获取FactoryBean本身
beanName = FACTORY_BEAN_PREFIX + beanName;
matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
}
}
if (matchFound) {
// 如果与类型匹配,则添加
result.add(beanName);
}
}
catch (CannotLoadBeanClassException | BeanDefinitionStoreException ex) {
// ... 代码省略
}
catch (NoSuchBeanDefinitionException ex) {
// ... 代码省略
}
}
}
// 检查手动注入的单例bean
for (String beanName : this.manualSingletonNames) {
try {
// FactoryBean需要特殊处理
if (isFactoryBean(beanName)) {
// 如果与类型匹配,则添加
if (isTypeMatch(beanName, type)) {
result.add(beanName);
continue;
}
// 如果不匹配,尝试 &beanName 获取FactoryBean本身
beanName = FACTORY_BEAN_PREFIX + beanName;
}
// 如果与类型匹配,则添加
if (isTypeMatch(beanName, type)) {
result.add(beanName);
}
}
catch (NoSuchBeanDefinitionException ex) {
// ... 代码省略
}
}
return StringUtils.toStringArray(result);
}
}
上面有一个方法没有解析,DefaultListableBeanFactory.isTypeMatch
,内容较多,有兴趣可以自行探索
DefaultListableBeanFactory.getBeansOfType
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
@Override
public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException {
return getBeansOfType(type, true, true);
}
@Override
@SuppressWarnings("unchecked")
public <T> Map<String, T> getBeansOfType(
@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException {
// 先获取bean名字集合
String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
// 创建结果集合
Map<String, T> result = CollectionUtils.newLinkedHashMap(beanNames.length);
for (String beanName : beanNames) {
try {
// 获取bean实例
Object beanInstance = getBean(beanName);
// 如果不是NullBean,则添加
if (!(beanInstance instanceof NullBean)) {
result.put(beanName, (T) beanInstance);
}
}
catch (BeanCreationException ex) {
// ... 代码省略
}
}
return result;
}
}
DefaultListableBeanFactory.findAnnotationOnBean
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
@Override
public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
throws NoSuchBeanDefinitionException {
return findMergedAnnotationOnBean(beanName, annotationType)
.synthesize(MergedAnnotation::isPresent).orElse(null);
}
private <A extends Annotation> MergedAnnotation<A> findMergedAnnotationOnBean(
String beanName, Class<A> annotationType) {
// 先获取类型
Class<?> beanType = getType(beanName);
// 如果bean类型存在,直接扫描beanType(类、方法、属性),如果有,直接返回
if (beanType != null) {
MergedAnnotation<A> annotation =
MergedAnnotations.from(beanType, SearchStrategy.TYPE_HIERARCHY).get(annotationType);
if (annotation.isPresent()) {
return annotation;
}
}
// 如果有定义beanName
if (containsBeanDefinition(beanName)) {
// 获取合并父bean定义的RootBeanDefinition
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// 如果beanClass存在,直接扫描beanClass,如果有,直接返回
if (bd.hasBeanClass()) {
Class<?> beanClass = bd.getBeanClass();
if (beanClass != beanType) {
MergedAnnotation<A> annotation =
MergedAnnotations.from(beanClass, SearchStrategy.TYPE_HIERARCHY).get(annotationType);
if (annotation.isPresent()) {
return annotation;
}
}
}
// 如果有factory-method配置,直接扫描factoryMethod,如果有,直接返回
Method factoryMethod = bd.getResolvedFactoryMethod();
if (factoryMethod != null) {
MergedAnnotation<A> annotation =
MergedAnnotations.from(factoryMethod, SearchStrategy.TYPE_HIERARCHY).get(annotationType);
if (annotation.isPresent()) {
return annotation;
}
}
}
// 如果没有,则返回MissingMergedAnnotation
return MergedAnnotation.missing();
}
}
这一小节留下 1 个点MergedAnnotations.from
待解析
DefaultListableBeanFactory.getBeanNamesForAnnotation
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
@Override
public String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType) {
List<String> result = new ArrayList<>();
// 先从beanDefinitionNames中找
for (String beanName : this.beanDefinitionNames) {
BeanDefinition bd = this.beanDefinitionMap.get(beanName);
if (bd != null && !bd.isAbstract() && findAnnotationOnBean(beanName, annotationType) != null) {
result.add(beanName);
}
}
// 再从manualSingletonNames中找
for (String beanName : this.manualSingletonNames) {
if (!result.contains(beanName) && findAnnotationOnBean(beanName, annotationType) != null) {
result.add(beanName);
}
}
return StringUtils.toStringArray(result);
}
}
DefaultListableBeanFactory.getBeansWithAnnotation
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
@Override
public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) {
// 先获取有annotationType注解的bean名字集合
String[] beanNames = getBeanNamesForAnnotation(annotationType);
// 创建结果Map
Map<String, Object> result = CollectionUtils.newLinkedHashMap(beanNames.length);
for (String beanName : beanNames) {
// 获取bean实例
Object beanInstance = getBean(beanName);
// 如果不是NullBean,则添加
if (!(beanInstance instanceof NullBean)) {
result.put(beanName, beanInstance);
}
}
return result;
}
}
DefaultListableBeanFactory.getBeanProvider
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
@Override
public <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType, boolean allowEagerInit) {
return getBeanProvider(ResolvableType.forRawClass(requiredType), allowEagerInit);
}
@Override
public <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType, boolean allowEagerInit) {
return new BeanObjectProvider<T>() {
@Override
public T getObject() throws BeansException {
// 获取requiredType的bean
T resolved = resolveBean(requiredType, null, false);
if (resolved == null) {
throw new NoSuchBeanDefinitionException(requiredType);
}
return resolved;
}
@Override
public T getObject(Object... args) throws BeansException {
// 获取requiredType的bean
T resolved = resolveBean(requiredType, args, false);
if (resolved == null) {
throw new NoSuchBeanDefinitionException(requiredType);
}
return resolved;
}
// ... 代码省略
@Override
public Stream<T> stream() {
// 获取包括祖先bean在内的,指定requiredType的bean名字集合
return Arrays.stream(getBeanNamesForTypedStream(requiredType, allowEagerInit))
.map(name -> (T) getBean(name))
.filter(bean -> !(bean instanceof NullBean));
}
// ... 代码省略
};
}
}
这里的核心是 resolveBean
方法
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
private <T> T resolveBean(ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) {
// 获取有命名的bean
NamedBeanHolder<T> namedBean = resolveNamedBean(requiredType, args, nonUniqueAsNull);
// 如果有命名的bean,直接返回
if (namedBean != null) {
return namedBean.getBeanInstance();
}
// 获取父beanFactory
BeanFactory parent = getParentBeanFactory();
if (parent instanceof DefaultListableBeanFactory) {
// 如果父beanFactory也是DefaultListableBeanFactory,直接调用resolveBean方法
return ((DefaultListableBeanFactory) parent).resolveBean(requiredType, args, nonUniqueAsNull);
}
else if (parent != null) {
// 获取beanProvider,通过beanProvider获取
ObjectProvider<T> parentProvider = parent.getBeanProvider(requiredType);
if (args != null) {
return parentProvider.getObject(args);
}
else {
return (nonUniqueAsNull ? parentProvider.getIfUnique() : parentProvider.getIfAvailable());
}
}
return null;
}
private <T> NamedBeanHolder<T> resolveNamedBean(
ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) throws BeansException {
// 通过类型requiredType获取bean名字集合
String[] candidateNames = getBeanNamesForType(requiredType);
// ... 代码省略
if (candidateNames.length == 1) {
// 如果只有一个,直接返回
return resolveNamedBean(candidateNames[0], requiredType, args);
}
else if (candidateNames.length > 1) {
Map<String, Object> candidates = CollectionUtils.newLinkedHashMap(candidateNames.length);
// ... 代码省略
// 获取标记为primary的bean
String candidateName = determinePrimaryCandidate(candidates, requiredType.toClass());
if (candidateName == null) {
// 没有获取标记为primary的bean,则选择@Order最高的bean
candidateName = determineHighestPriorityCandidate(candidates, requiredType.toClass());
}
if (candidateName != null) {
// 有了,获取实例
Object beanInstance = candidates.get(candidateName);
if (beanInstance == null) {
return null;
}
// 装载
if (beanInstance instanceof Class) {
return resolveNamedBean(candidateName, requiredType, args);
}
return new NamedBeanHolder<>(candidateName, (T) beanInstance);
}
// ... 代码省略
}
return null;
}
}
这一节主要介绍了 Bean 的注册、解析、实例化,但 bean 的构造装载与属性值解析,则留待后面再来解析了
这一节仍然有一些点留待下次解析:
ConstructorResolver.autowireConstructor
如何进行构造装载并实例化的CglibSubclassingInstantiationStrategy.instantiate
如何动态实例化 bean 的BeanDefinitionValueResolver.resolveValueIfNecessary
如何解析属性值的MergedAnnotations.from
如何扫描注解的更多博客,查看 https://github.com/senntyou/blogs
版权声明:自由转载-非商用-非衍生-保持署名(创意共享 3.0 许可证)
广播的原则 如果两个数组的后缘维度(从末尾开始算起的维度)的轴长度相符或其中一方的长度为1,则认为它们是广播兼容的。广播会在缺失维度和(或)轴长度为1的维度上进行。 在上面的对arr每一列减去列
之前在讲 MySQL 事务隔离性提到过,对于写操作给读操作的影响这种情形下发生的脏读、不可重复读、虚读问题。是通过MVCC 机制来进行解决的,那么MVCC到底是如何实现的,其内部原理是怎样的呢?我们要
我创建了一个 JavaScript 对象来保存用户在 ColorBox 中检查复选框时设置的值。 . 我对 jQuery 和“以正确的方式”编程 JavaScript 比较陌生,希望确保以下用于捕获用
我为了回答aquestion posted here on SO而玩示例,发现很难理解python的import *破坏作用域的机制。 首先是一点上下文:这个问题不涉及实际问题;我很清楚from fo
我想让我的类具有标识此类的参数 ID。例如我想要这样的东西: class Car { public static virtual string ID{get{return "car";}} }
更新:我使用的是 Java 1.6.34,没有机会升级到 Java 7。 我有一个场景,我每分钟只能调用一个方法 80 次。它实际上是由第 3 方编写的服务 API,如果您多次调用它,它会“关闭”(忽
希望这对于那些使用 Javascript 的人来说是一个简单的答案...... 我有一个日志文件,该文件正在被一个脚本监视,该脚本将注销中的新行提供给任何连接的浏览器。一些人评论说,他们希望看到的更多
我们正在开发针对 5.2 开发的 PHP 应用程序,但我们最近迁移到了 PHP 5.3。我们没有时间去解决所有迁移到 PHP 5.3 的问题。具体来说,我们有很多消息: Declaration of
简介 在实现定时调度功能的时候,我们往往会借助于第三方类库来完成,比如: quartz 、 spring schedule 等等。jdk从1.3版本开始,就提供了基于 timer 的定时调度功能。
Java中,一切都是对象,在分布式环境中经常需要将Object从这一端网络或设备传递到另一端。这就需要有一种可以在两端传输数据的协议。Java序列化机制就是为了解决这个问题而
我将编写自己的自定义控件,它与 UIButton 有很大不同。由于差异太大,我决定从头开始编写。所以我所有的子类都是 UIControl。 当我的控件在内部被触摸时,我想以目标操作的方式触发一条消息。
在我的代码中,在创建 TIdIMAP4 连接之前,我设置了一大堆 SASL 机制,希望按照规定的“最好到最差”顺序,如下所示: IMAP.SASLMechanisms.Add.SASL := mIdS
在 Kubernetes 中,假设我们有 3 个 pod,它们物理上托管在节点 X、Y 和 Z 上。当我使用“kubectl expose”将它们公开为服务时,它们都是集群中的节点(除了 X、Y 和
关闭。这个问题需要多问focused 。目前不接受答案。 想要改进此问题吗?更新问题,使其仅关注一个问题 editing this post . 已关闭 9 年前。 Improve this ques
我知道进程间通信 (ipc) 有几种方法,例如: 文件 信号 socket 消息队列 管道 命名管道 信号量 共享内存 消息传递 内存映射文件 但是我无法找到将这些机制相互比较并指出它们在不同环境中的
当我尝试连接到 teradata 时,出现了TD2 机制不支持单点登录 错误。 在 C# 中,我遇到了类似的问题,我通过添加 connectionStringBuilder.Authetication
我有一个带有 JSON API 的简单 Javascript 应用程序。目前它在客户端运行,但我想将它从客户端移动到服务器。我习惯于学习新平台,但在这种情况下,我的时间非常有限 - 所以我需要找到绝对
我想了解事件绑定(bind)/解除绑定(bind)在浏览器中是如何工作的。具体来说,如果我删除一个已经绑定(bind)了事件的元素,例如使用 jQuery:$("#anElement").remove
我不是在寻找具体答案,只是一个想法或提示。我有以下问题: Android 应用程序是 Web 服务的客户端。它有一个线程,通过 http 协议(protocol)发送事件(带有请求 ID 的 XML
我正在研究 FreeBSD TCP/IP 栈。似乎有 2 种 syn flood 机制,syncookies 和 syncache。我的问题是关于 syncookies,它是从头开始还是在 SYN 队
我是一名优秀的程序员,十分优秀!