# Spring框架(百度百科)
# 概述
Spring框架是由于软件开发的复杂性而创建的。
Spring使用的是基本的JavaBean来完成以前只可能由EJB完成的事情。
然而,Spring的用途不仅仅限于服务器端的开发。
从简单性、可测试性和松耦合性角度而言,绝大部分Java应用都可以从Spring中受益。
# 起源
j2EE应用程序开发的复杂性:
- J2EE应用程序的广泛实现是在1999年和2000年开始的,它的出现带来了诸如事务管理之类的核心中间层概念的标准化,但是在实践中并没有获得绝对的成功,因为开发效率,开发难度和实际的性能都令人失望。
EJB学习的复杂性:
- 在EJB开始的学习和应用非常的艰苦,很多东西都不能一下子就很容易的理解。
- 学习EJB的高昂代价,和极低的开发效率,极高的资源消耗,都造成了EJB的使用困难。
Spring的一个最大的目的就是使JAVA EE开发更加容易。Spring是一个提供了更完善开发环境的一个框架,可以为POJO(Plain Ordinary Java Object)对象提供企业级的服务。
Spring的形成,最初来自Rod Jahnson所著的一本很有影响力的书籍《Expert One-on-One J2EE Design and Development》,就是在这本书中第一次出现了Spring的一些核心思想,该书出版于2002年。
# 核心特点
轻量: 大小与开销两方面都是轻量的。完整的Spring框架可以在一个大小只有1MB多的JAR文件里发布。并且Spring所需的处理开销也是微不足道的。
控制反转: Spring通过一种称作控制反转(IoC)的技术促进了松耦合。一个对象依赖的其它对象会通过被动的方式传递进来,而不是这个对象自己创建或者查找依赖对象。不是对象从容器中查找依赖,而是容器在对象初始化时不等对象请求就主动将依赖传递给它。
面向切面: Spring提供了面向切面编程的丰富支持,允许通过分离应用的业务逻辑与系统级服务(例如审计(auditing)和事务(transaction)管理)进行内聚性的开发。
容器: Spring包含并管理应用对象的配置和生命周期,在这个意义上它是一种容器,你可以配置你的每个bean如何被创建——基于一个可配置原型(prototype),你的bean可以创建一个单独的实例或者每次需要时都生成一个新的实例——以及它们是如何相互关联的。
框架: Spring可以将简单的组件配置、组合成为复杂的应用。
# 模块组成(7个模块)
核心容器(Spring-Core): 最基本的概念是: BeanFactory. 它使得Spring成为了一个容器;
应用上下文模块(Spring-Context): 它使得Spring成为了一个框架. 扩展成为了ApplicationContext,增加了对 国际化,消息,事件传播及验证的支持;同时,他也提供了很多企业服务,如邮件,JNDI,调度等;
面向切面模块(Spring-AOP): 这个模块是在Spring应用中实现切面编程的基础。为了确保Spring与其它AOP框架的互用性,Spring的AOP支持基于AOP联盟定义的API。Spring的AOP模块也将元数据编程引入了Spring。
JDBC抽象和DAO模块(Spring-DAO): Spring的JDBC和DAO模块抽取了这些重复代码,因此你可以保持你的数据库访问代码干净简洁,并且可以防止因关闭数据库资源失败而引起的问题。这个模块还使用了Spring的AOP模块为Spring应用中的对象提供了事务管理服务。
对象/关系映射集成模块(Spring-ORM): Spring并不试图实现它自己的ORM解决方案,而是为几种流行的ORM框架提供了集成方案,包括Hibernate、JDO和iBATIS SQL映射。
Web模块(Spring-Web): Web上下文模块建立于应用上下文模块之上,提供了一个适合于Web应用的上下文。另外,这个模块还提供了一些面向服务支持。
MVC模块(Spring-WebMVC): Spring为构建Web应用提供了一个功能全面的MVC框架。虽然Spring可以很容易地与其它MVC框架集成,例如Struts,但Spring的MVC框架使用IoC对控制逻辑和业务对象提供了完全的分离。
# spring核心容器
# 核心容器抽象结构
public interface BeanFactory {
/*xxx: 根据指定的名称,从bean容器获取bean*/
Object getBean(String name) throws BeansException;
/*xxx: 根据指定的类型获取bean */
<T> T getBean(Class<T> requiredType) throws BeansException;
/*xxx: 检测指定名称的bean是否是单例*/
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
/*xxx: 检测指定名称的bean是否是原型模式*/
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
//省略其它抽象...
}
public interface HierarchicalBeanFactory extends BeanFactory {
/*xxx: 获取父容器*/
BeanFactory getParentBeanFactory();
/*xxx: 本层容器是否包含指定名称的bean */
boolean containsLocalBean(String name);
}
public interface AutowireCapableBeanFactory extends BeanFactory {
/*xxx: 创建bean实例*/
<T> T createBean(Class<T> beanClass) throws BeansException;
/*xxx: 注入已经存在的bean*/
void autowireBean(Object existingBean) throws BeansException;
/*xxx: 容器层面初始化bean*/
Object initializeBean(Object existingBean, String beanName) throws BeansException;
/*xxx: bean后置处理器,在容器层面的初始化前,调用*/
Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException;
/*xxx: bean后置处理器,在容器层面的初始化后,调用*/
Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException;
//省略其它抽象...
}
public interface ListableBeanFactory extends BeanFactory {
/*xxx: 获取容器中 beanDefinition的数量*/
int getBeanDefinitionCount();
/*xxx: 获取容器中 beanDefinition的名称数组*/
String[] getBeanDefinitionNames();
/*xxx: 获取指定注解的bean */
Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException;
/*xxx: 获取指定bean的注解集合*/
<A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
throws NoSuchBeanDefinitionException;
//省略其它抽象...
}
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
/*xxx: 设置父容器*/
void setParentBeanFactory(BeanFactory parentBeanFactory) throws IllegalStateException;
/*xxx: 添加bean的后置处理器*/
void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);
/*xxx: 注册指定的领域*/
void registerScope(String scopeName, Scope scope);
/*xxx: 为给定的bean,注册依赖的bean*/
void registerDependentBean(String beanName, String dependentBeanName);
//省略其它抽象...
}
public interface SingletonBeanRegistry {
/*xxx: 根据名称,注册单例对象*/
void registerSingleton(String beanName, Object singletonObject);
/*xxx: 根据名称,获取单例对象*/
Object getSingleton(String beanName);
/*xxx: 获取单例锁*/
Object getSingletonMutex();
//省略其它抽象...
}
public interface ConfigurableListableBeanFactory
extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory {
/*xxx: 自动注入时,忽略给定的类*/
void ignoreDependencyType(Class<?> type);
/*xxx: 自动注入时,忽略给定的接口*/
void ignoreDependencyInterface(Class<?> ifc);
/*xxx: 冻结所有的bean定义信息,不允许被修改*/
void freezeConfiguration();
//省略其它抽象...
}
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
protected <T> T doGetBean(
String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {
/*xxx: 如果是别名的话,就转为实际的名称*/
String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
/*xxx: 先从手动注册的单例缓存中,进行查找*/
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}/*xxx: 实例是手动注册的,并且没有指定初始化参数*/
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
/*xxx: 如果当前的bean正在创建中,则抛错*/
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
/*xxx: 获取父容器*/
BeanFactory parentBeanFactory = getParentBeanFactory();
/*xxx: 如果当前的容器没有找到bean,并且父容器存在,则从父容器中找*/
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
/*xxx: 如果父容器是抽象容器的子类,则通过调用全参的方式进行获取*/
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
/*xxx: 否则,通过顶级容器的参数进行获取*/
else if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
/*xxx: 如果父容器和子容器都没有找到相应的bean,并且没有指定类型检查*/
if (!typeCheckOnly) {
/*xxx: 则标记当前的bean名称已经被创建过*/
markBeanAsCreated(beanName);
}
/*xxx: 实例化钩子*/
StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")
.tag("beanName", name);
try {
if (requiredType != null) {
beanCreation.tag("beanType", requiredType::toString);
}
/*xxx: 以给定的名称,获取 RootBeanDefinition,获取不到,则会直接抛错*/
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
/*xxx: 获取beanDefinition的所有依赖项的bean的名称 */
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
/*xxx: 遍历依赖项*/
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
/*xxx: 如果不是依赖项,则抛错*/
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
/*xxx: 是依赖项,则进行注册*/
registerDependentBean(dep, beanName);
try {
/*xxx: 同时,初始化依赖项,如果依赖的bean有问题,则进行抛错*/
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
/*xxx: 创建本身的bean实例,如果是单例模式*/
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
/*xxx: 首次调用时,需要创建bean,创建后,即进行缓存 */
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;
}
}); /*xxx: 获取bean的对象实例,会自动处理工厂模式*/
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
/*xxx: 原型模式,每次都会创建一个新的实例,该新实例也会自动处理工厂模式 */
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 { /*xxx: 如果既非 单例模式,也非原型模式,则按照特定的领域规则进行处理*/
String scopeName = mbd.getScope();
if (!StringUtils.hasLength(scopeName)) {
throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
}
Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new ScopeNotActiveException(beanName, scopeName, ex);
}
}
}
catch (BeansException ex) {
beanCreation.tag("exception", ex.getClass().toString());
beanCreation.tag("message", String.valueOf(ex.getMessage()));
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
finally {
beanCreation.end();
}
}
// Check if required type matches the type of the actual bean instance.
/*xxx: 如果有指定bean的类型,则对其类型进行检查,如果不匹配,则*/
if (requiredType != null && !requiredType.isInstance(bean)) {
try {/*xxx: 调用类型转换服务,转换成指定的实例类型*/
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
protected abstract boolean containsBeanDefinition(String beanName);
protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;
protected abstract Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException;
//省略其它抽象...
}
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
/*xxx: 初始化bean的时候,会自动调用生成bean的相关回调操作*/
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
/*xxx: 在实例化bean的时候,调用了 bean后置处理器*/
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
/*xxx: 1.首先执行特定的感知器,默认情况下,指挥处理 beanName,classLoader,beanFactory.
其它已经存在的核心感知器(边缘感知器通过其它bean后置处理器实现)是通过 bean后置处理器完成的,具体而言,是由 ApplicationContextAwareProcessor 完成的(并且是 前置处理)。 它们默认情况下会在高级容器中生效 */
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
/*xxx: 2。执行bean后置处理器的初始化前置方法*/
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
/*xxx: 3.执行初始化方法: InitializingBean接口方法 或者 用户自定义的 init方法*/
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
/*xxx: 4.执行bean后置处理器的后置方法*/
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
/*xxx: bean后置处理器前置方法,如果返回空,意味着前置处理中断*/
if (current == null) {
return result;
}
result = current;
}
return result;
}
@Override
/*xxx: 该方法是应用于所有的后置处理器*/
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
/*xxx: bean实例后置处理,如果返回空,也意味着中断后置处理*/
if (current == null) {
return result;
}
result = current;
}
return result;
}
@Override
/*xxx: 创建bean实例*/
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
/*xxx: 如果bean的实例后置处理器存在,则bean实例的实例化是通过 bean实例后置处理器实现的*/
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
/*xxx: 实际创建bean的方法*/
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
//省略其它抽象...
}
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
@Override
public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
/*xxx: 从beanDefinitionMap缓存中进行获取,获取不到则直接报错*/
BeanDefinition bd = this.beanDefinitionMap.get(beanName);
if (bd == null) {
if (logger.isTraceEnabled()) {
logger.trace("No bean named '" + beanName + "' found in " + this);
}
throw new NoSuchBeanDefinitionException(beanName);
}
return bd;
}
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
/*xxx: 所有不是lazy-init的单例,都会在这里进行实例化*/
/*xxx: 这里的代码经过 编译优化后,会成为一个 需要维护 7层的循环*/
/*xxx: 遍历所有的bean名称 */
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
/*xxx: 如果被遍历的元素bean,不是抽象的,并且是单例,同时不是 lazyInit的时候*/
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
/*xxx: 如果是工厂bean,通过getObject获取实际的bean*/
if (isFactoryBean(beanName)) {
/*xxx: 如果是工厂bean,则先将该工厂bean拿到,工厂bean的名称 为&+ bean的名称*/
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
/*xxx: 拿到工厂bean后,进一步验证确保代码稳健*/
if (bean instanceof FactoryBean) {
/*xxx: 强转为 FactoryBean,这个在多层级抽象体系里特别重要,
在强转之前,前面通常有一个instanceof操作符,确保稳健性*/
FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged(
(PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
/*xxx: 当该工厂bean为智能工厂bean,同时它的属性为 eagerInit时,才能进行进行 实例化*/
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
/*xxx: 否则,则只实例化 工厂bean,而不获取实际的bean*/
}
}
else {
/*xxx: 否则直接调用getBean触发实例化*/
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
/*xxx: 触发所有的后置实例化回调为所有匹配的bean*/
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
/*xxx: 对所有单例,进行实例化后置检测*/
/*xxx: 当该单例为 智能实例化单例时*/
if (singletonInstance instanceof SmartInitializingSingleton) {
StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize")
.tag("beanName", beanName);
SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
/*xxx: 则对这个单例调用,实例化后置回调,只针对单例进行处理*/
smartSingleton.afterSingletonsInstantiated();
}
smartInitialize.end();
}
}
}
@Nullable
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
try {
Object shortcut = descriptor.resolveShortcut(this);
if (shortcut != null) {
return shortcut;
}
Class<?> type = descriptor.getDependencyType();
/*xxx: 注入bean时,该方法返回空,注入属性时,原样返回 */
Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
if (value != null) {
/*xxx: 如果需要注入的类型为String,则进行属性注入*/
if (value instanceof String) {
String strVal = resolveEmbeddedValue((String) value);
BeanDefinition bd = (beanName != null && containsBean(beanName) ?
getMergedBeanDefinition(beanName) : null);
value = evaluateBeanDefinitionString(strVal, bd);
}
TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
try {
/*xxx: 否则使用类型转换器进行转换*/
return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
}
catch (UnsupportedOperationException ex) {
// A custom TypeConverter which does not support TypeDescriptor resolution...
return (descriptor.getField() != null ?
converter.convertIfNecessary(value, type, descriptor.getField()) :
converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
}
}
/*xxx: 解析是否是注入多个bean, 即 待注入的类型为 数组,Map,或者Collection子类 */
Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
if (multipleBeans != null) {
return multipleBeans;
}
/*xxx: 查询待注入的候选bean */
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
if (matchingBeans.isEmpty()) {
if (isRequired(descriptor)) {
raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
}
return null;
}
String autowiredBeanName;
Object instanceCandidate;
/*xxx: 如果从容器中,查找到了多个符合条件的bean*/
if (matchingBeans.size() > 1) {
/*xxx: 调用该方法,决定采用哪个bean */
autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
if (autowiredBeanName == null) {
if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
}
else {
// In case of an optional Collection/Map, silently ignore a non-unique case:
// possibly it was meant to be an empty collection of multiple regular beans
// (before 4.3 in particular when we didn't even look for collection beans).
return null;
}
}
instanceCandidate = matchingBeans.get(autowiredBeanName);
}
else {
// We have exactly one match.
Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
autowiredBeanName = entry.getKey();
instanceCandidate = entry.getValue();
}
if (autowiredBeanNames != null) {
autowiredBeanNames.add(autowiredBeanName);
}
if (instanceCandidate instanceof Class) {
instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
}
Object result = instanceCandidate;
if (result instanceof NullBean) {
if (isRequired(descriptor)) {
raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
}
result = null;
}
if (!ClassUtils.isAssignableValue(type, result)) {
throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
}
return result;
}
finally {
ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
}
}
@Nullable
protected String determineAutowireCandidate(Map<String, Object> candidates, DependencyDescriptor descriptor) {
Class<?> requiredType = descriptor.getDependencyType();
/*xxx: 优先根据类型进行Primary的查找*/
String primaryCandidate = determinePrimaryCandidate(candidates, requiredType);
if (primaryCandidate != null) {
return primaryCandidate;
}
/*xxx: 其次,再查找高优先级的 候选项 */
String priorityCandidate = determineHighestPriorityCandidate(candidates, requiredType);
if (priorityCandidate != null) {
return priorityCandidate;
}
// Fallback
/*xxx: 都没找到,则用名称进行匹配*/
for (Map.Entry<String, Object> entry : candidates.entrySet()) {
String candidateName = entry.getKey();
Object beanInstance = entry.getValue();
if ((beanInstance != null && this.resolvableDependencies.containsValue(beanInstance)) ||
matchesBeanName(candidateName, descriptor.getDependencyName())) {
return candidateName;
}
}
return null;
}
//省略其它抽象...
}
public interface BeanDefinitionRegistry extends AliasRegistry {
/*xxx: 根据指定的名称,注册beanDefinition*/
void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException;
/*xxx: 根据指定名称,获取 beanDefinition */
BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
//省略其它抽象...
}
# 核心容器抽象层次说明
- 简单工厂
# 核心容器核心作用
提供Bean的托管功能
- 通过单例注册表,完成单例对象的管理
- 通过BeanDefinition注册表,完成对类的托管;
提供依赖注入的功能
提供bean对象的动态创建及销毁功能
是其它高级容器的基础
# Spring应用上下文容器
# 应用上下文容器抽象结构
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
MessageSource, ApplicationEventPublisher, ResourcePatternResolver {
@Nullable
/*xxx: 获取父上下文*/
ApplicationContext getParent();
//省略其它抽象...
}
public interface ApplicationEventPublisher {
/*xxx: 发布事件 (事件类型)*/
default void publishEvent(ApplicationEvent event) {
publishEvent((Object) event);
}
/*xxx: 发布事件(对象类型)*/
void publishEvent(Object event);
}
public interface EnvironmentCapable {
/*xxx: 获取应用的环境配置信息*/
Environment getEnvironment();
}
public interface ResourcePatternResolver extends ResourceLoader {
/*xxx: 获取路径下的资源数组*/
Resource[] getResources(String locationPattern) throws IOException;
}
public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {
/*xxx: 设置environment对象*/
void setEnvironment(ConfigurableEnvironment environment);
/*xxx: 添加容器后置处理器*/
/*xxx: 容器后置处理器,在任何bean定义得到应用。要在上下文配置期间调用的*/
void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor);
/*xxx: 添加应用监听器 */
void addApplicationListener(ApplicationListener<?> listener);
/*xxx: 由于这是一个启动方法,如果失败它应该销毁已经创建的单例,则避免悬而未决的资源。换句话说,在调用之后在这个方法中,要么全部实例化,要么根本不实例化*/
/*xxx: 加载或刷新配置的持久表示形式,这将可能来自基于Java的配置、XML文件、属性文件和关系数据库模式或其他格式。*/
void refresh() throws BeansException, IllegalStateException;
@Override
/*xxx: 关闭此应用程序上下文,释放所持有的资源和锁这包括销毁所有缓存的单例bean。*/
void close();
/*xxx: 判断当前的上下文是否为活跃状态*/
boolean isActive();
/*xxx: 获取当前上下文的内部bean容器*/
ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
//省略其它抽象...
}
public interface WebApplicationContext extends ApplicationContext {
@Nullable
/*xxx: 获取标准Servlet API规范的 servlet上下文*/
ServletContext getServletContext();
//省略其它抽象...
}
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
@Override
public void refresh() throws BeansException, IllegalStateException {
/*xxx: 同步锁*/
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// Prepare this context for refreshing.
/*xxx:准备用于刷新的上下文,该方法执行后,当前上下文的 actived 状态为真,environment被初始化。 同时,初始化应用启动前的应用监听器. */
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
/*xxx: 通知子类,刷新内部实际的bean工厂。 变更上下文的启动状态 refreshed 为true。 同时,在这个阶段,会进行beanDefinition的加载,包括 xml 以及 annotation */
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
/*xxx: 准备这个上下文即将使用的bean工厂。 主要就是设置 bean容器运行所必需的依赖,同时新增几个bean后置处理器,设置忽略注入的接口,以及设置特定的全局依赖(包括environment,startupDate等)*/
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
/*xxx: 标准bean工厂准备完后,为相应的子类提供bean工厂后置的处理
* 比如与web环境相关的上下文,会添加 ServletContextAwareProcessor*/
postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
/*xxx: 处理容器后置处理器,代理给PostProcessorRegistrationDelegate 进行处理*/
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
/*xxx: 注册bean后置处理器,将容器中的BeanFactory中定义的Bean后置处理器应用于bean容器*/
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// Initialize message source for this context.
/*xxx: 初始化这个上下文的数据源,也就是将messageSource进行实例化*/
initMessageSource();
// Initialize event multicaster for this context.
/*xxx: 初始化这个上下文的 应用事件广播器,既配置到上下文中,也将此容器注册到 bean容器中*/
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
/*xxx: 初始化其它在子上下文中的特定bean*/
onRefresh();
// Check for listener beans and register them.
/*xxx: 注册监听器*/
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
/*xxx: 实例化所有 不需要lazy-init的bean,以及所有的SmartInitializingSingleton*/
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
/*xxx:执行生命周期处理器处理*/
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
/*xxx: 如果在上下文启动过程中抛错了,则销毁上下文持有的锁,以及清除缓存*/
destroyBeans();
// Reset 'active' flag.
/*xxx: 重置active状态标志*/
cancelRefresh(ex);
// Propagate exception to caller.
/*xxx: 对外层抛出异常 */
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
/*xxx: 重置缓存,在重置缓存的时候,原生spring环境下,会触发工厂自动装载机制,但是无法装载bean */
resetCommonCaches();
/*xxx: 相当于释放锁的功能*/
contextRefresh.end();
}
}
}
protected void prepareRefresh() {
// Switch to active.
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
// Initialize any placeholder property sources in the context environment.
/*xxx: 初始化当前环境下的所有属性源*/
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
/*xxx: 验证所有被标注为必需的属性 是可被正确解析的*/
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
/*xxx: 存储所有预刷新的 应用监听器 */
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}
/*xxx: 获取装载后的上下文工厂*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
/*xxx: 抽象方法,交给子类实现*/
refreshBeanFactory();
/*xxx: 抽象方法,获得实际的 bean工厂,由子类实现*/
return getBeanFactory();
}
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
/*xxx:设置bean工厂的类加载器*/
beanFactory.setBeanClassLoader(getClassLoader());
if (!shouldIgnoreSpel) {
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
}
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
/*xxx:添加上下文感知的 bean后置处理器*/
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
beanFactory.ignoreDependencyInterface(ApplicationStartup.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
/*xxx:添加监听器感知的bean后置处理器*/
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (!IN_NATIVE_IMAGE && 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()));
}
// Register default environment beans.
/*xxx: 注册一些 应用级别的bean*/
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
}
}
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches();
// Initialize lifecycle processor for this context.
/*xxx: 初始化生命周期处理器*/
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
/*xxx: 触发生命周期处理器进行刷新*/
getLifecycleProcessor().onRefresh();
// Publish the final event.
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
if (!IN_NATIVE_IMAGE) {
LiveBeansView.registerApplicationContext(this);
}
}
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
/*xxx: 不再修改bean工厂中的bean定义信息*/
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
/*xxx: 实例化所有 没有 懒实例化的单例*/
beanFactory.preInstantiateSingletons();
}
@Override
/*xxx: 上下文启动方法*/
public void start() {
/*xxx: 生命周期处理器,会调用所有的生命周期的bean,执行启动方法*/
getLifecycleProcessor().start();
/*xxx: 将容器上下文的启动事件发布出去*/
publishEvent(new ContextStartedEvent(this));
}
@Override
/*xxx: 上下文停止方法*/
public void stop() {
/*xxx: 生命周期处理器,并遍历调用生命周期的bean,执行停止方法 */
getLifecycleProcessor().stop();
/*xxx: 发布上下文停止事件*/
publishEvent(new ContextStoppedEvent(this));
}
/*xxx: 刷新bean容器,通常在这个过程装载 beanDefinition,通过xml,或者注解*/
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
@Override
/*xxx: 获取bean容器 */
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
//省略其它抽象...
}
public interface ConfigurableWebApplicationContext extends WebApplicationContext, ConfigurableApplicationContext {
@Nullable
/*xxx: 获取web应用上下文的命名空间,如果有的话*/
String getNamespace();
@Nullable
/*xxx: 获取配置位置的数组*/
String[] getConfigLocations();
//省略其它抽象...
}
public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
/*xxx: bean容器 */
private final DefaultListableBeanFactory beanFactory;
/*xxx: 上下文是否已执行refresh方法 */
private final AtomicBoolean refreshed = new AtomicBoolean();
//省略其它抽象...
}
public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext {
@Override
protected final void refreshBeanFactory() throws BeansException {
/*xxx: 如果之前有bean工厂,就销毁bean工厂的所有bean,并且关闭bean工厂*/
if (hasBeanFactory()) {
/*xxx: 父类实现*/
destroyBeans();
/*xxx: 本类实现*/
closeBeanFactory();
}
try {
/*xxx:创建bean工厂,本类实现*/
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
/*xxx: 本地化bean工厂,主要设置 是否允许 bean覆盖 以及 bean的循环引用*/
customizeBeanFactory(beanFactory);
/*xxx: 加载bean,抽象方法,交给子类实现*/
loadBeanDefinitions(beanFactory);
this.beanFactory = beanFactory;
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
//省略其它抽象...
}
public abstract class AbstractRefreshableConfigApplicationContext extends AbstractRefreshableApplicationContext
implements BeanNameAware, InitializingBean {
@Nullable
protected String[] getConfigLocations() {
return (this.configLocations != null ? this.configLocations : getDefaultConfigLocations());
}
//省略其它抽象
}
public abstract class AbstractXmlApplicationContext extends AbstractRefreshableConfigApplicationContext {
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
initBeanDefinitionReader(beanDefinitionReader);
loadBeanDefinitions(beanDefinitionReader);
}
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = getConfigLocations();
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}
//省略其它抽象...
}
public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry {
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
this();
register(componentClasses);
refresh();
}
public AnnotationConfigApplicationContext() {
StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");
/*xxx: 在初始化该类时,会在工厂中注册一个 名称为 internalConfigurationAnnotationProcessor的 配置类工厂后置处理器*/
this.reader = new AnnotatedBeanDefinitionReader(this);
createAnnotatedBeanDefReader.end();
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
//省略其它抽象...
}
public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
//省略其它抽象
}
# 应用上下文核心功能说明
规定了容器使用的流程规范
- 在refresh方法之前,可以对容器环境进行配置,对容器中的 bean或者 beanDefinition进行装载
- 在refresh方法之后,不能再变动容器中的内容
- refresh方法中,本身定义了一套模板,该模板构成了应用上下文的核心,遵循特定的流程
在核心容器的基础上,增加了应用上下文容器后置处理器特性,它可以在refresh过程中,动态的装载BeanDefinition;
在核心容器的基础上,引入了 广播机制,自动启动生命周期的bean特性;
就加载BeanDefinition的方式而言,应用上下文提供了两种健全的方式,包括 xml配置方式 以及 Annotation注解方式
就核心功能而言,依然是由 核心容器完成的,但是应用上下文对其进行了优雅的封装,使得功能更易使用,更加强大。
# bean的生成及缓存
# bean的生成方式
todo:后续补充
# bean的缓存方式
todo: 后续补充
# 后置处理器
# 容器后置处理器
todo:后续补充
# bean后置处理器
todo:后续补充
# 生命周期处理器
# 生命周期体系结构
todo: 后续补充
# 生命周期bean执行逻辑
todo: 后续补充
# 事件发布机制
# 事件发布机制设计体系
todo: 后续补充
# 事件发布机制的执行逻辑
todo: 后续补充
# BeanDefinition体系
# 什么是BeanDefinition
来自于博客: Bean与BeanDefinition的理解——理解spring的基础和关键 (opens new window)
- BeanDefinition是bean在spring中的描述,有了BeanDefinition我们就可以创建Bean,BeanDefinition是Bean在spring中的定义形态。
- 通过这个 BeanDefinition 定义的数据结构,容器能够方便地对 Bean 进行管理。
# 抽象结构
public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {
/*xxx: 设置beanDefinition指代的类的名称*/
void setBeanClassName(@Nullable String beanClassName);
/*xxx: 获取beanDefinition指代的作用域 */
String getScope();
/*xxx: 获取当前的beanDefinition是否懒加载 */
boolean isLazyInit();
/*xxx: 判断当前的bean是否为主要的自动装配候选。*/
boolean isPrimary();
//省略其它抽象...
}
public interface AttributeAccessor {
/*xxx: 设置属性*/
void setAttribute(String name, @Nullable Object value);
/*xxx: 获取属性*/
Object getAttribute(String name);
//省略其它抽象...
}
public interface BeanMetadataElement {
/*xxx: 返回这个元素据对象 */
default Object getSource() {
return null;
}
}
# BeanDefinition的结构

- 核心抽象实现:
AbstractBeanDefinition
- 常用实现类:
RootBeanDefinition
,GenericBeanDefinition
(推荐)
# xml方式加载bean
# XmlBeanDefinitionReader 的抽象结构
/*xxx: 顶级接口: beanDefinition读取器*/
public interface BeanDefinitionReader {
/*xxx: 获取beanDefinition注册表*/
BeanDefinitionRegistry getRegistry();
/*xxx: 从资源句柄中,加载beanDefinition */
int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException;
@Nullable
/*xxx: 获取资源句柄加载器*/
ResourceLoader getResourceLoader();
//省略其它抽象...
}
/*xxx: 抽象beanDefinition 读取解析器 */
public abstract class AbstractBeanDefinitionReader implements BeanDefinitionReader, EnvironmentCapable {
public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
ResourceLoader resourceLoader = getResourceLoader();
if (resourceLoader == null) {
throw new BeanDefinitionStoreException(
"Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
}
if (resourceLoader instanceof ResourcePatternResolver) {
// Resource pattern matching available.
try {
//xxx: 根据资源加载器,加载到资源句柄
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
//xxx: 实际加载资源的动作,由子类完成
int count = loadBeanDefinitions(resources);
if (actualResources != null) {
Collections.addAll(actualResources, resources);
}
if (logger.isTraceEnabled()) {
logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
}
return count;
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"Could not resolve bean definition resource pattern [" + location + "]", ex);
}
}
else {
// Can only load single resources by absolute URL.
Resource resource = resourceLoader.getResource(location);
int count = loadBeanDefinitions(resource);
if (actualResources != null) {
actualResources.add(resource);
}
if (logger.isTraceEnabled()) {
logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
}
return count;
}
}
}
public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {
@Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
}
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isTraceEnabled()) {
logger.trace("Loading XML bean definitions from " + encodedResource);
}
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
/*xxx: 如果之前已经加载过,则抛错 */
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"IOException parsing XML document from " + encodedResource.getResource(), ex);
}
finally {
currentResources.remove(encodedResource);
if (currentResources.isEmpty()) {
this.resourcesCurrentlyBeingLoaded.remove();
}
}
}
/*xxx: 从指定的 xml文件中,加载beanDefinition的配置 */
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
/*xxx: 将xml文件中的内容,通过 xml领域相关类,创建Document文档 */
Document doc = doLoadDocument(inputSource, resource);
int count = registerBeanDefinitions(doc, resource);
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + count + " bean definitions from " + resource);
}
return count;
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (SAXParseException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
}
catch (SAXException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"XML document from " + resource + " is invalid", ex);
}
catch (ParserConfigurationException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Parser configuration exception parsing XML from " + resource, ex);
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"IOException parsing XML document from " + resource, ex);
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Unexpected exception parsing XML document from " + resource, ex);
}
}
protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
getValidationModeForResource(resource), isNamespaceAware());
}
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
int countBefore = getRegistry().getBeanDefinitionCount();
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getRegistry().getBeanDefinitionCount() - countBefore;
}
}
# xml加载Bean的说明
- 根据路径,封装为资源句柄
- 根据 资源句柄,读取为
Document
对象。 - 通过
BeanDefinitionDocumentReader
从Document
读取出BeanDefinition
,并进行注册。 读取过程,依赖于EntityResolver
.
/*xxx: 顶级接口: document领域文档读取 beanDefinition*/
public interface BeanDefinitionDocumentReader {
/*xxx: 从文档中读取beanDefinition,并进行缓存 */
void registerBeanDefinitions(Document doc, XmlReaderContext readerContext)
throws BeanDefinitionStoreException;
}
public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocumentReader {
protected void doRegisterBeanDefinitions(Element root) {
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createDelegate(getReaderContext(), root, parent);
if (this.delegate.isDefaultNamespace(root)) {
String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
if (StringUtils.hasText(profileSpec)) {
String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
// We cannot use Profiles.of(...) since profile expressions are not supported
// in XML config. See SPR-12458 for details.
if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
if (logger.isDebugEnabled()) {
logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
"] not matching: " + getReaderContext().getResource());
}
return;
}
}
}
preProcessXml(root);
parseBeanDefinitions(root, this.delegate);
postProcessXml(root);
this.delegate = parent;
}
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
if (delegate.isDefaultNamespace(root)) {
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element ele = (Element) node;
/*xxx: 默认命名空间的节点,<beans>*/
if (delegate.isDefaultNamespace(ele)) {
parseDefaultElement(ele, delegate);
}
else {
/*xxx: 除了beans命名空间下的节点,其它都是客户端节点 */
delegate.parseCustomElement(ele);
}
}
}
}
else {
delegate.parseCustomElement(root);
}
}
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
if (delegate.nodeNameEquals(ele, "import")) {
importBeanDefinitionResource(ele);
}
else if (delegate.nodeNameEquals(ele, "alias")) {
processAliasRegistration(ele);
}
else if (delegate.nodeNameEquals(ele, "bean")) {
processBeanDefinition(ele, delegate);
}
else if (delegate.nodeNameEquals(ele, "beans")) {
// recurse
doRegisterBeanDefinitions(ele);
}
}
}
# NamespaceHandler 的作用
- 处理 自定义命名空间元素节点
/*xxx: beanDefinition的解析代理 */
public class BeanDefinitionParserDelegate {
@Nullable
/*xxx: 解析客户端节点 */
public BeanDefinition parseCustomElement(Element ele) {
return parseCustomElement(ele, null);
}
@Nullable
/*xxx: 解析客户端节点 */
public BeanDefinition parseCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
/*xxx: 获取当前元素的命名空间*/
String namespaceUri = getNamespaceURI(ele);
if (namespaceUri == null) {
return null;
}
/*xxx: 在资源句柄,读取为Document的过程中, 依赖 spring.schemas 以及 spring-xxx.xsd文件*/
/*xxx: 进行namespace映射时,需要依赖映射文件: spring.handlers */
NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
if (handler == null) {
error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
return null;
}
return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
}
}
# NamespaceHandler 的抽象结构及运行逻辑
public interface NamespaceHandler {
void init();
@Nullable
BeanDefinition parse(Element element, ParserContext parserContext);
//省略其它抽象...
}
public abstract class NamespaceHandlerSupport implements NamespaceHandler {
@Override
@Nullable
/*xxx: 用于将 配置的标签 转换成 spring 需要的 BeanDefinition*/
public BeanDefinition parse(Element element, ParserContext parserContext) {
BeanDefinitionParser parser = findParserForElement(element, parserContext);
return (parser != null ? parser.parse(element, parserContext) : null);
}
}
/*xxx: 自定义实现的命名解析器*/
public static class AtmNameSpaceHandler extends NamespaceHandlerSupport {
public void init() {
/*xxx: 这里只需要处理,最顶级的节点即可,嵌套的元素节点,需要再内层处理*/
registerBeanDefinitionParser("atmBean",new AtmBeanHandler());
registerBeanDefinitionParser("refer",new ReferBeanHandler());
}
}
/*xxx: 自定义实现的一个解析器*/
public static class AtmBeanHandler implements BeanDefinitionParser {
public BeanDefinition parse(Element element, ParserContext parserContext) {
System.out.println("处理atmBean节点,可以获取到相应的属性,进行处理,主要是转化为 beanDefinition");
System.out.println(element.getAttributes());
System.out.println("转换后的 beanDefinition,自然会放到容器中. 完成无缝对接");
System.out.println("内层元素需要继续进行解析");
GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
genericBeanDefinition.setBeanClass(BusinessBean.class);
return genericBeanDefinition;
}
}
# 特殊的命名空间处理器: spring-context
<context:component-scan base-packet="xxx.xxx.xxx">
public class ContextNamespaceHandler extends NamespaceHandlerSupport {
@Override
public void init() {
registerBeanDefinitionParser("property-placeholder", new PropertyPlaceholderBeanDefinitionParser());
registerBeanDefinitionParser("property-override", new PropertyOverrideBeanDefinitionParser());
registerBeanDefinitionParser("annotation-config", new AnnotationConfigBeanDefinitionParser());
registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser());
registerBeanDefinitionParser("load-time-weaver", new LoadTimeWeaverBeanDefinitionParser());
registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());
registerBeanDefinitionParser("mbean-export", new MBeanExportBeanDefinitionParser());
registerBeanDefinitionParser("mbean-server", new MBeanServerBeanDefinitionParser());
}
}
public class ComponentScanBeanDefinitionParser implements BeanDefinitionParser {
@Override
@Nullable
public BeanDefinition parse(Element element, ParserContext parserContext) {
String basePackage = element.getAttribute(BASE_PACKAGE_ATTRIBUTE);
basePackage = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(basePackage);
/*xxx: 可以指定多个路径 */
String[] basePackages = StringUtils.tokenizeToStringArray(basePackage,
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
// Actually scan for bean definitions and register them.
/*xxx: 创建一个扫描器,用于扫描指定路径的beanDefinition */
ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);
Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);
registerComponents(parserContext.getReaderContext(), beanDefinitions, element);
return null;
}
protected ClassPathBeanDefinitionScanner configureScanner(ParserContext parserContext, Element element) {
boolean useDefaultFilters = true;
if (element.hasAttribute(USE_DEFAULT_FILTERS_ATTRIBUTE)) {
useDefaultFilters = Boolean.parseBoolean(element.getAttribute(USE_DEFAULT_FILTERS_ATTRIBUTE));
}
// Delegate bean definition registration to scanner class.
ClassPathBeanDefinitionScanner scanner = createScanner(parserContext.getReaderContext(), useDefaultFilters);
scanner.setBeanDefinitionDefaults(parserContext.getDelegate().getBeanDefinitionDefaults());
scanner.setAutowireCandidatePatterns(parserContext.getDelegate().getAutowireCandidatePatterns());
if (element.hasAttribute(RESOURCE_PATTERN_ATTRIBUTE)) {
scanner.setResourcePattern(element.getAttribute(RESOURCE_PATTERN_ATTRIBUTE));
}
try {
parseBeanNameGenerator(element, scanner);
}
catch (Exception ex) {
parserContext.getReaderContext().error(ex.getMessage(), parserContext.extractSource(element), ex.getCause());
}
try {
parseScope(element, scanner);
}
catch (Exception ex) {
parserContext.getReaderContext().error(ex.getMessage(), parserContext.extractSource(element), ex.getCause());
}
parseTypeFilters(element, scanner, parserContext);
return scanner;
}
/*xxx: 根据扫描到的内容,注册组件 */
protected void registerComponents(
XmlReaderContext readerContext, Set<BeanDefinitionHolder> beanDefinitions, Element element) {
Object source = readerContext.extractSource(element);
CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), source);
for (BeanDefinitionHolder beanDefHolder : beanDefinitions) {
compositeDef.addNestedComponent(new BeanComponentDefinition(beanDefHolder));
}
// Register annotation config processors, if necessary.
boolean annotationConfig = true;
if (element.hasAttribute(ANNOTATION_CONFIG_ATTRIBUTE)) {
annotationConfig = Boolean.parseBoolean(element.getAttribute(ANNOTATION_CONFIG_ATTRIBUTE));
}
if (annotationConfig) {
Set<BeanDefinitionHolder> processorDefinitions =
/*xxx: 注意,此处会主次容器后置处理器 */
AnnotationConfigUtils.registerAnnotationConfigProcessors(readerContext.getRegistry(), source);
for (BeanDefinitionHolder processorDefinition : processorDefinitions) {
compositeDef.addNestedComponent(new BeanComponentDefinition(processorDefinition));
}
}
readerContext.fireComponentRegistered(compositeDef);
}
//省略其它抽象...
}
/*xxx: 注解配置工具类*/
public abstract class AnnotationConfigUtils {
/*xxx: 注册注解配置处理器*/
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
}
}
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
/*xxx: 注册 internalConfigurationAnnotationProcessor*/
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
/*xxx: 将internalConfigurationAnnotationProcessor注册进容器*/
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
/*xxx: 注册 internalAutowaredAnnotationProcessor*/
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
/*xxx: 注册 internalCommonAnnotationProcessor*/
if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
/*xxx: 注册 internalPersistenceAnnotationProcessor*/
if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition();
try {
def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
AnnotationConfigUtils.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
}
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
}
/*xxx: 注册 internalEventListenerProcessor*/
if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
}
/*xxx: 注册 internalEventListenerFactory,只是单纯的注册一个工厂*/
if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
}
return beanDefs;
}
}
# annotation方式加载bean
# scanner的抽象结构
/*xxx: 类路径扫描候选容器提供者*/
public class ClassPathScanningCandidateComponentProvider implements EnvironmentCapable, ResourceLoaderAware {
/*xxx: 默认的资源模式*/
static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";
/*xxx: 查找候选组件,扫描的核心方法*/
public Set<BeanDefinition> findCandidateComponents(String basePackage) {
if (this.componentsIndex != null && indexSupportsIncludeFilters()) {
return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);
}
else {
/*xxx: 从包路径中,扫描候选组件 */
return scanCandidateComponents(basePackage);
}
}
/*xxx: 从包路径中,扫描候选组件*/
private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
Set<BeanDefinition> candidates = new LinkedHashSet<>();
try {
/*xxx: classpath*下,所有的资源, 如: classpath*:com/automannn/practice/**\/*.class*/
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
resolveBasePackage(basePackage) + '/' + this.resourcePattern;
/*xxx: 获取到所有的文件系统资源句柄*/
Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
boolean traceEnabled = logger.isTraceEnabled();
boolean debugEnabled = logger.isDebugEnabled();
/*xxx: 遍历加载到的文件句柄 */
for (Resource resource : resources) {
if (traceEnabled) {
logger.trace("Scanning " + resource);
}
if (resource.isReadable()) {
try {
/*xxx: 获取每个资源句柄的 元数据读取器 */
MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
/*xxx: 对所有获取到的文件,进行判断,是否是组件*/
/*xxx: 在此处就会进行 Condition条件判定*/
if (isCandidateComponent(metadataReader)) {
/*xxx: 直接将读取到的封装为 beanDefinition*/
ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
sbd.setSource(resource);
if (isCandidateComponent(sbd)) {
if (debugEnabled) {
logger.debug("Identified candidate component class: " + resource);
}
candidates.add(sbd);
}
else {
if (debugEnabled) {
logger.debug("Ignored because not a concrete top-level class: " + resource);
}
}
}
else {
if (traceEnabled) {
logger.trace("Ignored because not matching any filter: " + resource);
}
}
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to read candidate component class: " + resource, ex);
}
}
else {
if (traceEnabled) {
logger.trace("Ignored because not readable: " + resource);
}
}
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
}
return candidates;
}
/*xxx: 判断是否是组件时,具有两个匹配条件*/
/*xxx: 如果 需要排除的过滤器中,任意一个命中,则排除。
如果在 任意一个需要包括的过滤器中,则再次判断是否满足条件,否则都为false */
/*xxx: 默认情况下,需要处理: @Component,@ManagedBean,@Named注解*/
protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
for (TypeFilter tf : this.excludeFilters) {
if (tf.match(metadataReader, getMetadataReaderFactory())) {
return false;
}
}
for (TypeFilter tf : this.includeFilters) {
if (tf.match(metadataReader, getMetadataReaderFactory())) {
return isConditionMatch(metadataReader);
}
}
return false;
}
//省略其它抽象...
}
/*xxx: 类路径下 beanDefinition扫描器 */
public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider {
public int scan(String... basePackages) {
/*xxx: 记录没有扫描之前,容器中beanDefinition的个数*/
int beanCountAtScanStart = this.registry.getBeanDefinitionCount();
/*xxx:进行扫描,在这个过程中,会自动注册beanDefinition */
doScan(basePackages);
// Register annotation config processors, if necessary.
/*xxx: 如果开启了包含注解配置*/
if (this.includeAnnotationConfig) {
/*xxx: 则需要在当前的 beanDefinition注册表中,讲 注解配置后置处理器给注册进去*/
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
/*xxx: 返回扫描注册的个数*/
return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart);
}
/*xxx: 进行实际的扫描动作 */
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
/*xxx: 需要扫描的包不能为空,可以有多个*/
Assert.notEmpty(basePackages, "At least one base package must be specified");
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
/*xxx: 遍历多个需要扫描的包*/
for (String basePackage : basePackages) {
/*xxx: 从扫描的包路径中,查找候选组件 */
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
/*xxx: 对每一个候选组件,进行配置 */
for (BeanDefinition candidate : candidates) {
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
candidate.setScope(scopeMetadata.getScopeName());
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
/*xxx: 使用命名生成器,生成bean的名称(如果没有指定)*/
if (candidate instanceof AbstractBeanDefinition) {
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
if (candidate instanceof AnnotatedBeanDefinition) {
/*xxx: 如果扫描的到的 beanDefinition为注解类型,则需要处理通用的注解*/
AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
}
/*xxx: 检测是否有同名的bean,没有就进行注册*/
if (checkCandidate(beanName, candidate)) {
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
definitionHolder =
AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
beanDefinitions.add(definitionHolder);
/*xxx: 将扫描到的beanDefinition注册到注册表中 */
registerBeanDefinition(definitionHolder, this.registry);
}
}
}
return beanDefinitions;
}
//省略其它抽象
}
# 内置注解相关的容器后置处理器
- 配置类后置处理器
/*xxx: 配置类后置处理器,是一个容器后置处理器*/
public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor,
PriorityOrdered, ResourceLoaderAware, ApplicationStartupAware, BeanClassLoaderAware, EnvironmentAware {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
/*xxx: 后置处理beanDefinition的时候,首先对当前的注册表生成hash值*/
int registryId = System.identityHashCode(registry);
if (this.registriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
}
if (this.factoriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + registry);
}
/*xxx: 并将该hash值,作为已经处理的凭证 */
this.registriesPostProcessed.add(registryId);
/*xxx: 处理配置bean的流程*/
processConfigBeanDefinitions(registry);
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
int factoryId = System.identityHashCode(beanFactory);
if (this.factoriesPostProcessed.contains(factoryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + beanFactory);
}
this.factoriesPostProcessed.add(factoryId);
/*xxx: 如果当前的容器还没有被处理过,则进行处理*/
if (!this.registriesPostProcessed.contains(factoryId)) {
// BeanDefinitionRegistryPostProcessor hook apparently not supported...
// Simply call processConfigurationClasses lazily at this point then.
/*xxx: 处理配置bean的流程*/
processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory);
}
/*xxx: 工厂后置处理方法,对配置类进行加强处理*/
/*xxx: 作用之一,是将 beanDefinition指定的类名,同时设置好类实例*/
enhanceConfigurationClasses(beanFactory);
/*xxx: 添加 Import bean后置处理器*/
beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory));
}
/*xxx: 处理配置bean的流程 */
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
/*xxx: 从该工厂获取所有的BeanDefinition的名称*/
String[] candidateNames = registry.getBeanDefinitionNames();
for (String beanName : candidateNames) {
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
/*xxx: 如果该BeanDefinition含有: org.springframework.context.annotation.ConfigurationClassPostProcessor.class.configurationClass 属性,则代表已经被解析*/
if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
if (logger.isDebugEnabled()) {
logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
}
}
/*xxx: 如果该类具有 @Configuration注解,则根据它的 proxyBeanMethods属性,
决定 org.springframework.context.annotation.ConfigurationClassPostProcessor.class.configurationClass 属性 为full 还是 lite
猜想字面理解是 轻量级 和 重量级 的意思
spring5.2开始,默认都是重量级
*/
else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
}
/*xxx:没有找到 带有 @Configuration的类,则直接出栈*/
// Return immediately if no @Configuration classes were found
if (configCandidates.isEmpty()) {
return;
}
/*xxx: 将当前工厂中,所有带有@Configration的配置类,进行排序 自然序*/
// Sort by previously determined @Order value, if applicable
configCandidates.sort((bd1, bd2) -> {
int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
return Integer.compare(i1, i2);
});
// Detect any custom bean name generation strategy supplied through the enclosing application context
/*xxx: 获取bean名称生成器*/
SingletonBeanRegistry sbr = null;
if (registry instanceof SingletonBeanRegistry) {
sbr = (SingletonBeanRegistry) registry;
if (!this.localBeanNameGeneratorSet) {
BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
if (generator != null) {
this.componentScanBeanNameGenerator = generator;
this.importBeanNameGenerator = generator;
}
}
}
if (this.environment == null) {
this.environment = new StandardEnvironment();
}
// Parse each @Configuration class
/*xxx: 将该工厂 组装成 配置类解析器
* 这个配置类解析器,是解析 @Configuration类的核心实现*/
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);
/*xxx: 这里设计了两个集合,一个表示 即将进行解析的配置类,一个表示 已经解析的配置类*/
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
/*xxx: 对配置类结束解析的条件是: 只要 即将进行解析的配置类集合 为空, 那么表示整个解析过程完成*/
do {
StartupStep processConfig = this.applicationStartup.start("spring.context.config-classes.parse");
/*xxx: 配置类解析器 负责单个解析类的解析,核心的核心 是解析的重中之重*/
parser.parse(candidates);
parser.validate();
/*xxx: 对单个 解析类 中,新加入的配置类,需要首先进行排除已经解析过的解析类
* 一个典型的场景有可能是 多个 ComponentSan的扫描重合区域,包含了@Configration的 情况*/
Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
configClasses.removeAll(alreadyParsed);
// Read the model and create bean definitions based on its content
/*xxx: 载入相应的配置bean*/
if (this.reader == null) {
this.reader = new ConfigurationClassBeanDefinitionReader(
registry, this.sourceExtractor, this.resourceLoader, this.environment,
this.importBeanNameGenerator, parser.getImportRegistry());
}
/*xxx: 同时会将前序装载的 registrar钟的内容进行注册*/
/*xxx: 根据前期解析的结果,进行装载*/
this.reader.loadBeanDefinitions(configClasses);
/*xxx: 移除已经解析的配置类*/
alreadyParsed.addAll(configClasses);
processConfig.tag("classCount", () -> String.valueOf(configClasses.size())).end();
/*xxx:清空即将解析的配置类*/
candidates.clear();
/*xxx: 如果工厂中bean定义的个数 大于 初始的 注册bean的个数,则对当前的 即将解析配置类 进行调整
* 这个调整 的作用在于 处理单个配置类 引入的其它外部配置类,确保当前的工厂中所有的配置类,均被解析 */
if (registry.getBeanDefinitionCount() > candidateNames.length) {
String[] newCandidateNames = registry.getBeanDefinitionNames();
Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
Set<String> alreadyParsedClasses = new HashSet<>();
/*xxx: 维护了一个 新的待解析的配置类,老的配置类 以及 已经解析的类*/
for (ConfigurationClass configurationClass : alreadyParsed) {
alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
}
for (String candidateName : newCandidateNames) {
if (!oldCandidateNames.contains(candidateName)) {
BeanDefinition bd = registry.getBeanDefinition(candidateName);
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
!alreadyParsedClasses.contains(bd.getBeanClassName())) {
/*xxx: 对工厂中,新的bean,同时含有 @Configuration ,并且没有被解析的配置类,加入到 原有的待解析的配置集合中
* 触发新一轮的本流程*/
/*xxx: 这个新的配置类,主要来自于 @ImportResource, 以及 registrar 生成*/
candidates.add(new BeanDefinitionHolder(bd, candidateName));
}
}
}
candidateNames = newCandidateNames;
}
}
while (!candidates.isEmpty());
// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
}
if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
// Clear cache in externally provided MetadataReaderFactory; this is a no-op
// for a shared cache since it'll be cleared by the ApplicationContext.
((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
}
}
}
- 自动注入后置处理
/*xxx: 自动注入 注解后置处理器,是一个 bean后置处理器*/
public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor,
MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
public AutowiredAnnotationBeanPostProcessor() {
/*xxx: 自动注入,会处理 @Autowired @Value */
this.autowiredAnnotationTypes.add(Autowired.class);
this.autowiredAnnotationTypes.add(Value.class);
try {
this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
logger.trace("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
}
catch (ClassNotFoundException ex) {
// JSR-330 API not available - simply skip.
}
}
/*xxx: 处理自动注入*/
public void processInjection(Object bean) throws BeanCreationException {
Class<?> clazz = bean.getClass();
InjectionMetadata metadata = findAutowiringMetadata(clazz.getName(), clazz, null);
try {
metadata.inject(bean, null, null);
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
"Injection of autowired dependencies failed for class [" + clazz + "]", ex);
}
}
//省略其它抽象...
}
public class InjectionMetadata {
/*xxx: 无论是属性,还是变量,都是通过该方法进行注入的 */
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Collection<InjectedElement> checkedElements = this.checkedElements;
Collection<InjectedElement> elementsToIterate =
(checkedElements != null ? checkedElements : this.injectedElements);
if (!elementsToIterate.isEmpty()) {
for (InjectedElement element : elementsToIterate) {
if (logger.isTraceEnabled()) {
logger.trace("Processing injected element of bean '" + beanName + "': " + element);
}
element.inject(target, beanName, pvs);
}
}
}
public abstract static class InjectedElement {
protected abstract void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs)
throws Throwable;
}
//省略其它抽象...
}
private class AutowiredFieldElement extends InjectionMetadata.InjectedElement {
@Override
/*xxx: 进行属性bean,或者参数的注入 */
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Field field = (Field) this.member;
Object value;
if (this.cached) {
value = resolvedCachedArgument(beanName, this.cachedFieldValue);
}
else {
DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
desc.setContainingClass(bean.getClass());
Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
Assert.state(beanFactory != null, "No BeanFactory available");
TypeConverter typeConverter = beanFactory.getTypeConverter();
try {
/*xxx: 该方法会从容器中解析依赖的bean或者属性参数*/
value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
}
synchronized (this) {
if (!this.cached) {
if (value != null || this.required) {
this.cachedFieldValue = desc;
registerDependentBeans(beanName, autowiredBeanNames);
if (autowiredBeanNames.size() == 1) {
String autowiredBeanName = autowiredBeanNames.iterator().next();
if (beanFactory.containsBean(autowiredBeanName) &&
beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
this.cachedFieldValue = new ShortcutDependencyDescriptor(
desc, autowiredBeanName, field.getType());
}
}
}
else {
this.cachedFieldValue = null;
}
this.cached = true;
}
}
}
if (value != null) {
/*xxx: 属性注入,是通过反射完成的*/
ReflectionUtils.makeAccessible(field);
field.set(bean, value);
}
}
}
//省略其它抽象...
}
private class AutowiredMethodElement extends InjectionMetadata.InjectedElement {
@Override
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
if (checkPropertySkipping(pvs)) {
return;
}
Method method = (Method) this.member;
Object[] arguments;
if (this.cached) {
// Shortcut for avoiding synchronization...
arguments = resolveCachedArguments(beanName);
}
else {
int argumentCount = method.getParameterCount();
arguments = new Object[argumentCount];
DependencyDescriptor[] descriptors = new DependencyDescriptor[argumentCount];
Set<String> autowiredBeans = new LinkedHashSet<>(argumentCount);
Assert.state(beanFactory != null, "No BeanFactory available");
TypeConverter typeConverter = beanFactory.getTypeConverter();
for (int i = 0; i < arguments.length; i++) {
MethodParameter methodParam = new MethodParameter(method, i);
DependencyDescriptor currDesc = new DependencyDescriptor(methodParam, this.required);
currDesc.setContainingClass(bean.getClass());
descriptors[i] = currDesc;
try {
Object arg = beanFactory.resolveDependency(currDesc, beanName, autowiredBeans, typeConverter);
if (arg == null && !this.required) {
arguments = null;
break;
}
arguments[i] = arg;
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(methodParam), ex);
}
}
synchronized (this) {
if (!this.cached) {
if (arguments != null) {
DependencyDescriptor[] cachedMethodArguments = Arrays.copyOf(descriptors, arguments.length);
registerDependentBeans(beanName, autowiredBeans);
if (autowiredBeans.size() == argumentCount) {
Iterator<String> it = autowiredBeans.iterator();
Class<?>[] paramTypes = method.getParameterTypes();
for (int i = 0; i < paramTypes.length; i++) {
String autowiredBeanName = it.next();
if (beanFactory.containsBean(autowiredBeanName) &&
beanFactory.isTypeMatch(autowiredBeanName, paramTypes[i])) {
cachedMethodArguments[i] = new ShortcutDependencyDescriptor(
descriptors[i], autowiredBeanName, paramTypes[i]);
}
}
}
this.cachedMethodArguments = cachedMethodArguments;
}
else {
this.cachedMethodArguments = null;
}
this.cached = true;
}
}
}
if (arguments != null) {
try {
ReflectionUtils.makeAccessible(method);
method.invoke(bean, arguments);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
}
# 配置类的解析
/*xxx: 配置类解析器 */
class ConfigurationClassParser {
/*xxx: 进行解析 */
public void parse(Set<BeanDefinitionHolder> configCandidates) {
/*xxx:遍历处理 本次 即将解析的 所有 配置类
* 注意,此刻的入参,均为带有 @Configuration的配置类*/
for (BeanDefinitionHolder holder : configCandidates) {
BeanDefinition bd = holder.getBeanDefinition();
try {
/*xxx: 根据配置类的具体情况,调用相应的解析方法*/
if (bd instanceof AnnotatedBeanDefinition) {
parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
}
else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
}
else {
parse(bd.getBeanClassName(), holder.getBeanName());
}
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
}
}
this.deferredImportSelectorHandler.process();
}
protected final void parse(Class<?> clazz, String beanName) throws IOException {
processConfigurationClass(new ConfigurationClass(clazz, beanName), DEFAULT_EXCLUSION_FILTER);
}
/*xxx: 实际解析配置类的方法*/
protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) throws IOException {
/*xxx: 首先,如果当前的 配置类,不符合配置要求,则跳过*/
if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
return;
}
ConfigurationClass existingClass = this.configurationClasses.get(configClass);
/*xxx: 如果当前的配置类,已经在前面的过程中被解析过,则要么忽略 出栈,要么进行替换*/
if (existingClass != null) {
if (configClass.isImported()) {
if (existingClass.isImported()) {
existingClass.mergeImportedBy(configClass);
}
// Otherwise ignore new imported config class; existing non-imported class overrides it.
return;
}
else {
// Explicit bean definition found, probably replacing an import.
// Let's remove the old one and go with the new one.
this.configurationClasses.remove(configClass);
this.knownSuperclasses.values().removeIf(configClass::equals);
}
}
// Recursively process the configuration class and its superclass hierarchy.
SourceClass sourceClass = asSourceClass(configClass, filter);
/*xxx: 从这个类的层级关系进行解析*/
do {
sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
}
while (sourceClass != null);
/*xxx:解析完成后,进行缓存,缓存的是每个配置类*/
this.configurationClasses.put(configClass, configClass);
}
@Nullable
protected final SourceClass doProcessConfigurationClass(
ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
throws IOException {
/*xxx: 1.首先解析 @Component的注解,即将配置类本身注册为beanDefinition*/
if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
// Recursively process any member (nested) classes first
processMemberClasses(configClass, sourceClass, filter);
}
/*xxx:2.然后解析@PropertySources注解*/
// Process any @PropertySource annotations
for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), PropertySources.class,
PropertySource.class)) {
if (this.environment instanceof ConfigurableEnvironment) {
processPropertySource(propertySource);
}
else {
logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
"]. Reason: Environment must implement ConfigurableEnvironment");
}
}
/*xxx:3.解析 ComponentScan注解*/
// Process any @ComponentScan annotations
Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
if (!componentScans.isEmpty() &&
!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
for (AnnotationAttributes componentScan : componentScans) {
// The config class is annotated with @ComponentScan -> perform the scan immediately
/*xxx:具有 @ComponentScan的配置类,立即进行扫描*/
Set<BeanDefinitionHolder> scannedBeanDefinitions =
this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
// Check the set of scanned definitions for any further config classes and parse recursively if needed
for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
if (bdCand == null) {
bdCand = holder.getBeanDefinition();
}
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
/*xxx: 对所有被componentScan扫描到的 所有配置类,进行解析
* 包括:轻量级的 @Component,@ComponentScan,@Import,@ImportResource 以及 重量级的 @Configuration
* 实际上,整个流程就构成了一棵 树形结构的 深度遍历*/
parse(bdCand.getBeanClassName(), holder.getBeanName());
}
}
}
}
/*xxx: 处理 @Import注解*/
// Process any @Import annotations
processImports(configClass, sourceClass, getImports(sourceClass), filter, true);
/*xxx: 处理 @ImportResource注解,这种情况下,可以把 xml配置文件 给引入进来*/
// Process any @ImportResource annotations
AnnotationAttributes importResource =
AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
if (importResource != null) {
String[] resources = importResource.getStringArray("locations");
Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
for (String resource : resources) {
String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
/*xxx: 处理 @ImportResource,也是将其进行暂存,然后在后续的处理流程中进行处理*/
configClass.addImportedResource(resolvedResource, readerClass);
}
}
/*xxx: 处理 本身的 @Bean方法*/
// Process individual @Bean methods
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {
/*xxx: 对@Bean的处理,也是放置在缓存中,后续进行处理 */
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}
// Process default methods on interfaces
/*xxx: 处理默认的接口方法*/
processInterfaces(configClass, sourceClass);
// Process superclass, if any
/*xxx: 遍历取出超类*/
if (sourceClass.getMetadata().hasSuperClass()) {
String superclass = sourceClass.getMetadata().getSuperClassName();
if (superclass != null && !superclass.startsWith("java") &&
!this.knownSuperclasses.containsKey(superclass)) {
this.knownSuperclasses.put(superclass, configClass);
// Superclass found, return its annotation metadata and recurse
return sourceClass.getSuperClass();
}
}
// No superclass -> processing is complete
return null;
}
/*xxx: 处理引入配置,selector 或者 registrar 本身也会作为一个 配置类进行循环调用 */
private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
Collection<SourceClass> importCandidates, Predicate<String> exclusionFilter,
boolean checkForCircularImports) {
if (importCandidates.isEmpty()) {
return;
}
/*xxx: 判断是否循环引入,并入引用栈*/
if (checkForCircularImports && isChainedImportOnStack(configClass)) {
this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
}
else {
this.importStack.push(configClass);
try {
for (SourceClass candidate : importCandidates) {
/*xxx: 如果引入的是 ImportSelector,则根据条件进行引入配置*/
if (candidate.isAssignable(ImportSelector.class)) {
// Candidate class is an ImportSelector -> delegate to it to determine imports
Class<?> candidateClass = candidate.loadClass();
ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class,
this.environment, this.resourceLoader, this.registry);
Predicate<String> selectorFilter = selector.getExclusionFilter();
if (selectorFilter != null) {
exclusionFilter = exclusionFilter.or(selectorFilter);
}
/*xxx: 分为直接处理 import,以及异步处理import*/
if (selector instanceof DeferredImportSelector) {
this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
}
else {
/*xxx: 根据条件,检出需要装载的类, 被装载的类会走一遍自身的递归流程*/
String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, exclusionFilter);
processImports(configClass, currentSourceClass, importSourceClasses, exclusionFilter, false);
}
}
/*xxx: 如果引入的是 ImportBeanDefinitionRegistrar*/
else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
// Candidate class is an ImportBeanDefinitionRegistrar ->
// delegate to it to register additional bean definitions
Class<?> candidateClass = candidate.loadClass();
/*xxx:如果引入配置的类是 ImportaBeanDefinitionRegistrar的子类,则在这里 处理动态引入bean的操作*/
ImportBeanDefinitionRegistrar registrar =
ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
this.environment, this.resourceLoader, this.registry);
/*xxx: 将该registrar进行缓存,在后续流程中,进行处理*/
configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
}
else {
// Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
// process it as an @Configuration class
/*xxx: 如果引入的类,既不是 ImportSelector,也不是 ImportBeanDefinitionRegistrar,则把它当作 配置类来进行处理*/
this.importStack.registerImport(
currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
processConfigurationClass(candidate.asConfigClass(configClass), exclusionFilter);
}
}
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to process import candidates for configuration class [" +
configClass.getMetadata().getClassName() + "]", ex);
}
finally {
this.importStack.pop();
}
}
}
//省略其它抽象...
}
# 在注解环境使用xml配置
/*xxx: 配置类解析器 */
class ConfigurationClassParser {
@Nullable
protected final SourceClass doProcessConfigurationClass(
ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
throws IOException {
//...
/*xxx: 处理 @ImportResource注解,这种情况下,可以把 xml配置文件 给引入进来*/
// Process any @ImportResource annotations
AnnotationAttributes importResource =
AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
if (importResource != null) {
String[] resources = importResource.getStringArray("locations");
Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
for (String resource : resources) {
String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
/*xxx: 处理 @ImportResource,也是将其进行暂存,然后在后续的处理流程中进行处理*/
configClass.addImportedResource(resolvedResource, readerClass);
}
}
//...
return null;
}
//省略其它抽象...
}
# 两类常见上下文
# ClassPathXmlApplicationContext
public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {
public ClassPathXmlApplicationContext(String[] paths, Class<?> clazz, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
Assert.notNull(paths, "Path array must not be null");
Assert.notNull(clazz, "Class argument must not be null");
this.configResources = new Resource[paths.length];
for (int i = 0; i < paths.length; i++) {
this.configResources[i] = new ClassPathResource(paths[i], clazz);
}
refresh();
}
//省略其它抽象...
}
public abstract class AbstractXmlApplicationContext extends AbstractRefreshableConfigApplicationContext {
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
initBeanDefinitionReader(beanDefinitionReader);
loadBeanDefinitions(beanDefinitionReader);
}
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = getConfigLocations();
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}
//省略其它抽象...
}
# AnnotationConfigApplication
/*xxx: 基于 注解配置的 应用上下文。 */
public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry {
public AnnotationConfigApplicationContext() {
StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");
/*xxx: 在初始化该类时,会在工厂中注册一个 名称为 internalConfigurationAnnotationProcessor的 配置类工厂后置处理器*/
this.reader = new AnnotatedBeanDefinitionReader(this);
createAnnotatedBeanDefReader.end();
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
public AnnotationConfigApplicationContext(String... basePackages) {
this();
scan(basePackages);
refresh();
}
@Override
public void scan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
StartupStep scanPackages = this.getApplicationStartup().start("spring.context.base-packages.scan")
.tag("packages", () -> Arrays.toString(basePackages));
this.scanner.scan(basePackages);
scanPackages.end();
}
//省略其它抽象
}
- 二者区别:
- xml形式,依赖的是 AbstractRefreshableApplicationContext完成容器中 BeanDefinition的填充;
- annotation形式,依赖的是 GenericApplicationContext,其加载逻辑,由本身实现,靠 sanner完成;
- 二者区别在于,加载beanDefinition的方式不同,但是 内部的处理逻辑是浑然一体的。
# 切面编程
# 切面编程的关键类及抽象
- 代理工厂
/*xxx: 顶级接口: 获取类的类型*/
public interface TargetClassAware {
@Nullable
Class<?> getTargetClass();
}
/*xxx: 被通知的对象,即需要动态代理的对象 */
public interface Advised extends TargetClassAware {
/*xxx: 是否是在代理类,而非接口 */
boolean isProxyTargetClass();
/*xxx: 追加一个通知到通知链尾部 (在内部处理成一个 通知器)*/
void addAdvice(Advice advice) throws AopConfigException;
/*xxx: 为当前的通知器链 添加一个通知器 */
void addAdvisor(Advisor advisor) throws AopConfigException;
//省略其它抽象
}
/*xxx: 被代理对象包装器*/
public class AdvisedSupport extends ProxyConfig implements Advised {
//省略其它抽象
}
/*xxx: 动态代理生成器*/
public class ProxyCreatorSupport extends AdvisedSupport {
/*xxx: 创建aop动态代理*/
protected final synchronized AopProxy createAopProxy() {
if (!this.active) {
activate();
}
/*xxx:通过 aop动态代理工厂 创建 aop动态代理*/
return getAopProxyFactory().createAopProxy(this);
}
//省略其它抽象...
}
/*xxx: 代理工厂*/
public class ProxyFactory extends ProxyCreatorSupport {
public ProxyFactory(Object target) {
/*xxx: 允许实例化时,指定被代理的类,也就是AOP应用的 基础*/
setTarget(target);
/*xxx: 提取被代理对象的所有接口*/
setInterfaces(ClassUtils.getAllInterfaces(target));
}
/*xxx: 获取代理对象,具有多个重载方法,最终都是通过这个流程完成*/
public Object getProxy() {
return createAopProxy().getProxy();
}
//省略其它抽象...
}
- 动态代理
/*xxx: 顶级接口,aop动态代理接口 */
public interface AopProxy {
/*xxx: 获取动态代理对象(被编织后的对象)*/
Object getProxy();
}
/*xxx: jdk动态代理对象,它的实现,主要依靠 InvocationHandler 提供,具体的实现,由jdk实现 */
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
}
/*xxx: 通过JDK的Proxy完成动态代理类的编织*/
return Proxy.newProxyInstance(classLoader, this.proxiedInterfaces, this);
}
@Override
@Nullable
/*xxx: 第二个参数方法为实际要执行的方法,这个流程就是 对需要执行的方法,获取匹配了它的所有通知器*/
/*xxx: 该方法也是 jdk动态代理实现的核心 */
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object oldProxy = null;
boolean setProxyContext = false;
/*xxx: 获取被代理对象的类信息 */
TargetSource targetSource = this.advised.targetSource;
Object target = null;
try {
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
/*xxx: 如果被代理对象没有重写 equals方法,则调用本地的方法。 比较的是被代理对象*/
return equals(args[0]);
}
else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
/*xxx: 如果被代理对象没有重写 hashCode 方法,则调用本地的 hashCode 方法。*/
return hashCode();
}
else if (method.getDeclaringClass() == DecoratingProxy.class) {
// There is only getDecoratedClass() declared -> dispatch to proxy config.
/*xxx: 如果实现了 DecoratingProxy的方法,则 分发给代理配置 */
return AopProxyUtils.ultimateTargetClass(this.advised);
}
else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
method.getDeclaringClass().isAssignableFrom(Advised.class)) {
// Service invocations on ProxyConfig with the proxy config...
/*xxx: 使用代理配置在ProxyConfig上调用服务*/
return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
}
/*xxx: 返回值*/
Object retVal;
/*xxx: 如果需要暴露至 threadLocal,则进行暴露 */
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
// Get as late as possible to minimize the time we "own" the target,
// in case it comes from a pool.
/*xxx: 获取被代理对象*/
target = targetSource.getTarget();
/*xxx: 对被代理类进行非空安全检查*/
Class<?> targetClass = (target != null ? target.getClass() : null);
// Get the interception chain for this method.
/*xxx: 获取被代理类的当前方法的拦截器链 */
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
// Check whether we have any advice. If we don't, we can fallback on direct
// reflective invocation of the target, and avoid creating a MethodInvocation.
/*xxx: 如果没有匹配的通知器,则直接通过反射进行调用*/
if (chain.isEmpty()) {
// We can skip creating a MethodInvocation: just invoke the target directly
// Note that the final invoker must be an InvokerInterceptor so we know it does
// nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
}
else {
// We need to create a method invocation...
/*xxx: 根据切面的配置,构造方法执行链*/
MethodInvocation invocation =
new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
// Proceed to the joinpoint through the interceptor chain.
/*xxx:通过过滤器链逐步执行连接点,每一个拦截器即是一个连接点 */
retVal = invocation.proceed();
}
// Massage return value if necessary.
Class<?> returnType = method.getReturnType();
if (retVal != null && retVal == target &&
returnType != Object.class && returnType.isInstance(proxy) &&
!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
// Special case: it returned "this" and the return type of the method
// is type-compatible. Note that we can't help if the target sets
// a reference to itself in another returned object.
retVal = proxy;
}
else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
throw new AopInvocationException(
"Null return value from advice does not match primitive return type for: " + method);
}
return retVal;
}
finally {
if (target != null && !targetSource.isStatic()) {
// Must have come from TargetSource.
targetSource.releaseTarget(target);
}
if (setProxyContext) {
// Restore old proxy.
AopContext.setCurrentProxy(oldProxy);
}
}
}
//省略其它抽象...
}
/*xxx: cglib的动态代理实现 */
class CglibAopProxy implements AopProxy, Serializable {
@Override
/*xxx: 获取动态代理对象 */
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource());
}
try {
/*xxx: 获取需要被代理的对象 */
Class<?> rootClass = this.advised.getTargetClass();
Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");
Class<?> proxySuperClass = rootClass;
/*xxx: 如果已经被代理过,则获取原始对象 */
if (rootClass.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)) {
proxySuperClass = rootClass.getSuperclass();
Class<?>[] additionalInterfaces = rootClass.getInterfaces();
/*xxx: 将原始类需要被实现的接口进行重写 */
for (Class<?> additionalInterface : additionalInterfaces) {
this.advised.addInterface(additionalInterface);
}
}
// Validate the class, writing log messages as necessary.
/*xxx: 对类进行合法性验证 */
validateClassIfNecessary(proxySuperClass, classLoader);
// Configure CGLIB Enhancer...
/*xxx: 创建 Enhancer 实例对象 */
Enhancer enhancer = createEnhancer();
if (classLoader != null) {
enhancer.setClassLoader(classLoader);
if (classLoader instanceof SmartClassLoader &&
((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
enhancer.setUseCache(false);
}
}
/*xxx: 设置需要被代理的类 */
enhancer.setSuperclass(proxySuperClass);
/*xxx: 设置需要被代理的接口 */
enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(classLoader));
Callback[] callbacks = getCallbacks(rootClass);
Class<?>[] types = new Class<?>[callbacks.length];
for (int x = 0; x < types.length; x++) {
types[x] = callbacks[x].getClass();
}
// fixedInterceptorMap only populated at this point, after getCallbacks call above
enhancer.setCallbackFilter(new ProxyCallbackFilter(
this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
/*xxx: 设置回调拦截器*/
enhancer.setCallbackTypes(types);
// Generate the proxy class and create a proxy instance.
/*xxx: 创建cglib动态代理实例*/
return createProxyClassAndInstance(enhancer, callbacks);
}
catch (CodeGenerationException | IllegalArgumentException ex) {
throw new AopConfigException("Could not generate CGLIB subclass of " + this.advised.getTargetClass() +
": Common causes of this problem include using a final class or a non-visible class",
ex);
}
catch (Throwable ex) {
// TargetSource.getTarget() failed
throw new AopConfigException("Unexpected AOP exception", ex);
}
}
/*xxx: 获取切面操作,也就是Callback */
private Callback[] getCallbacks(Class<?> rootClass) throws Exception {
// Parameters used for optimization choices...
boolean exposeProxy = this.advised.isExposeProxy();
boolean isFrozen = this.advised.isFrozen();
boolean isStatic = this.advised.getTargetSource().isStatic();
// Choose an "aop" interceptor (used for AOP calls).
/*xxx: 创建 cgLib层面的 动态切面拦截器,动态代理编织主要通过它完成*/
Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised);
// Choose a "straight to target" interceptor. (used for calls that are
// unadvised but can return this). May be required to expose the proxy.
Callback targetInterceptor;
if (exposeProxy) {
targetInterceptor = (isStatic ?
new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :
new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource()));
}
else {
targetInterceptor = (isStatic ?
new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :
new DynamicUnadvisedInterceptor(this.advised.getTargetSource()));
}
// Choose a "direct to target" dispatcher (used for
// unadvised calls to static targets that cannot return this).
Callback targetDispatcher = (isStatic ?
new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp());
/*xxx: 将切面包装成拦截器链*/
Callback[] mainCallbacks = new Callback[] {
aopInterceptor, // for normal advice
targetInterceptor, // invoke target without considering advice, if optimized
new SerializableNoOp(), // no override for methods mapped to this
targetDispatcher, this.advisedDispatcher,
new EqualsInterceptor(this.advised),
new HashCodeInterceptor(this.advised)
};
Callback[] callbacks;
// If the target is a static one and the advice chain is frozen,
// then we can make some optimizations by sending the AOP calls
// direct to the target using the fixed chain for that method.
if (isStatic && isFrozen) {
Method[] methods = rootClass.getMethods();
Callback[] fixedCallbacks = new Callback[methods.length];
this.fixedInterceptorMap = CollectionUtils.newHashMap(methods.length);
// TODO: small memory optimization here (can skip creation for methods with no advice)
for (int x = 0; x < methods.length; x++) {
Method method = methods[x];
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, rootClass);
fixedCallbacks[x] = new FixedChainStaticTargetInterceptor(
chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetClass());
this.fixedInterceptorMap.put(method, x);
}
// Now copy both the callbacks from mainCallbacks
// and fixedCallbacks into the callbacks array.
callbacks = new Callback[mainCallbacks.length + fixedCallbacks.length];
System.arraycopy(mainCallbacks, 0, callbacks, 0, mainCallbacks.length);
System.arraycopy(fixedCallbacks, 0, callbacks, mainCallbacks.length, fixedCallbacks.length);
this.fixedInterceptorOffset = mainCallbacks.length;
}
else {
callbacks = mainCallbacks;
}
return callbacks;
}
//省略其它抽象...
/*xxx: aop与cglib 的结合原理*/
private static class DynamicAdvisedInterceptor implements MethodInterceptor, Serializable {
@Override
@Nullable
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Object oldProxy = null;
boolean setProxyContext = false;
Object target = null;
TargetSource targetSource = this.advised.getTargetSource();
try {
/*xxx: 是否需要暴露到 threadLocal */
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
// Get as late as possible to minimize the time we "own" the target, in case it comes from a pool...
target = targetSource.getTarget();
Class<?> targetClass = (target != null ? target.getClass() : null);
/*xxx: 获取 通知器链*/
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
Object retVal;
// Check whether we only have one InvokerInterceptor: that is,
// no real advice, but just reflective invocation of the target.
if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
// We can skip creating a MethodInvocation: just invoke the target directly.
// Note that the final invoker must be an InvokerInterceptor, so we know
// it does nothing but a reflective operation on the target, and no hot
// swapping or fancy proxying.
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = methodProxy.invoke(target, argsToUse);
}
else {
// We need to create a method invocation...
retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
}
retVal = processReturnType(proxy, target, method, retVal);
return retVal;
}
finally {
if (target != null && !targetSource.isStatic()) {
targetSource.releaseTarget(target);
}
if (setProxyContext) {
// Restore old proxy.
AopContext.setCurrentProxy(oldProxy);
}
}
}
//省略其它抽象
}
}
- 连接点
/*xxx: 连接点 */
public interface Joinpoint {
@Nullable
/*xxx: 处理链上的下一个拦截器*/
Object proceed() throws Throwable;
}
/*xxx: 当前接口代表程序中的一次执行 */
public interface Invocation extends Joinpoint {
@Nonnull
/*xxx: 获取参数数组*/
Object[] getArguments();
}
/*xxx: 描述一个方法的执行*/
public interface MethodInvocation extends Invocation {
@Nonnull
/*xxx: 获取需要被调用的方法 */
Method getMethod();
}
/*xxx: 用于在方法执行准备过程中,进行动态代理*/
public interface ProxyMethodInvocation extends MethodInvocation {
//省略其它抽象...
}
/*xxx: 反射方法调用的连接点 */
public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Cloneable {
@Override
@Nullable
public Object proceed() throws Throwable {
/*xxx: 该方法为 jdk的AOP实现的核心 */
// We start with an index of -1 and increment early.
/*xxx: 从拦截器链条的尾部向头部进行递归执行*/
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
}
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
/*xxx: 如果通知器为 动态方法匹配拦截器,则还需要方法是否匹配的验证 */
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
// Evaluate dynamic method matcher here: static part will already have
// been evaluated and found to match.
InterceptorAndDynamicMethodMatcher dm =
(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {
return dm.interceptor.invoke(this);
}
else {
// Dynamic matching failed.
// Skip this interceptor and invoke the next in the chain.
return proceed();
}
}
else {
// It's an interceptor, so we just invoke it: The pointcut will have
// been evaluated statically before this object was constructed.
/*xxx: 获取通知,并进行执行 */
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
//省略其它抽象
}
/*xxx: cglib的方法反射调用 */
private static class CglibMethodInvocation extends ReflectiveMethodInvocation {
@Override
@Nullable
/*xxx: 连接点的流转*/
public Object proceed() throws Throwable {
try {
return super.proceed();
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
if (ReflectionUtils.declaresException(getMethod(), ex.getClass())) {
throw ex;
}
else {
throw new UndeclaredThrowableException(ex);
}
}
}
//省略其它抽象...
}
- 拦截器
/*xxx:顶级接口,通知*/
public interface Advice {
}
/*xxx: 拦截器*/
public interface Interceptor extends Advice {
}
@FunctionalInterface
/*xxx: 方法拦截器*/
public interface MethodInterceptor extends Interceptor {
@Nullable
/*xxx: 执行方法 */
Object invoke(@Nonnull MethodInvocation invocation) throws Throwable;
}
@FunctionalInterface
/*xxx: 方法拦截器*/
public interface MethodInterceptor extends Interceptor {
@Nullable
/*xxx: 执行方法 */
Object invoke(@Nonnull MethodInvocation invocation) throws Throwable;
}
# 自动代理的实现方式
- 自动代理配置类
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {
}
/*xxx: 动态代理的bean生成处理器*/
class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(
AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
/*xxx: 这个方法在工厂中,注册了一个 AspectJ注解的自动代理生成器*/
AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
AnnotationAttributes enableAspectJAutoProxy =
AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
/*xxx: 这里类似于工厂后置方法,根据注解,修改bean定义*/
if (enableAspectJAutoProxy != null) {
if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
}
if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
}
}
}
}
public abstract class AopConfigUtils {
@Nullable
public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
/*xxx: 在当前上下文中注入 AspectJAnnotation自动代理生成器*/
return registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry, null);
}
@Nullable
public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(
BeanDefinitionRegistry registry, @Nullable Object source) {
return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
}
//省略其它抽象...
}
- 自动代理生成器
public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator {
@Override
protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
super.initBeanFactory(beanFactory);
if (this.aspectJAdvisorFactory == null) {
/*xxx: 实例化 反射切面Aspectj通知器工厂*/
this.aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory);
}
/*xxx: 实例化 aspecjt通知器构造器*/
this.aspectJAdvisorsBuilder =
new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this.aspectJAdvisorFactory);
}
//省略其它抽象...
}
public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator {
//省略抽象...
}
public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {
@Override
@Nullable
/*xxx: 为指定的bean,获取拦截切面 */
protected Object[] getAdvicesAndAdvisorsForBean(
Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
if (advisors.isEmpty()) {
return DO_NOT_PROXY;
}
return advisors.toArray();
}
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
/*xxx: 获取所有的切面*/
List<Advisor> candidateAdvisors = findCandidateAdvisors();
/*xxx: 从所有的切面中进行筛选 */
List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
extendAdvisors(eligibleAdvisors);
if (!eligibleAdvisors.isEmpty()) {
eligibleAdvisors = sortAdvisors(eligibleAdvisors);
}
return eligibleAdvisors;
}
/*xxx: 获取匹配的拦截器 */
protected List<Advisor> findAdvisorsThatCanApply(
List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
ProxyCreationContext.setCurrentProxiedBeanName(beanName);
try {
return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
}
finally {
ProxyCreationContext.setCurrentProxiedBeanName(null);
}
}
//省略抽象...
}
/*xxx: 该类为aop内部使用提供支持*/
public abstract class AopUtils {
/*xxx: 从给定的预备通知器中,筛选出满足切点的通知器*/
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
if (candidateAdvisors.isEmpty()) {
return candidateAdvisors;
}
List<Advisor> eligibleAdvisors = new ArrayList<>();
for (Advisor candidate : candidateAdvisors) {
if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
eligibleAdvisors.add(candidate);
}
}
boolean hasIntroductions = !eligibleAdvisors.isEmpty();
for (Advisor candidate : candidateAdvisors) {
if (candidate instanceof IntroductionAdvisor) {
// already processed
continue;
}
if (canApply(candidate, clazz, hasIntroductions)) {
eligibleAdvisors.add(candidate);
}
}
return eligibleAdvisors;
}
/*xxx: 判断给定的切面是否匹配*/
public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) {
if (advisor instanceof IntroductionAdvisor) {
/*xxx: IntroductionAdvisor,根据类过滤器,进行匹配 */
return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
}
else if (advisor instanceof PointcutAdvisor) {
PointcutAdvisor pca = (PointcutAdvisor) advisor;
/*xxx: PointcutAdvisor,检测目标类是否满足切点条件*/
return canApply(pca.getPointcut(), targetClass, hasIntroductions);
}
else {
// It doesn't have a pointcut so we assume it applies.
return true;
}
}
/*xxx: 检测目标类是否满足切点条件*/
public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) {
Assert.notNull(pc, "Pointcut must not be null");
/*xxx:首先会经过类过滤器进行过滤*/
if (!pc.getClassFilter().matches(targetClass)) {
return false;
}
MethodMatcher methodMatcher = pc.getMethodMatcher();
/*xxx:然后会通过切点的方法匹配策略 进行匹配*/
if (methodMatcher == MethodMatcher.TRUE) {
// No need to iterate the methods if we're matching any method anyway...
return true;
}
IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
}
Set<Class<?>> classes = new LinkedHashSet<>();
if (!Proxy.isProxyClass(targetClass)) {
/*xxx:目标对象没有采用jdk动态代理,则要么是cglib代理,要么没有代理,获取到没有代理的原始类*/
classes.add(ClassUtils.getUserClass(targetClass));
}
/*xxx: 获取到目标类的所有的超类接口*/
classes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
for (Class<?> clazz : classes) {
/*xxx:获取目标类即接口的方法,只要有一个方法满足切点条件,即视为切点可以匹配*/
Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
for (Method method : methods) {
/*xxx:对目标类和方法进行切点验证*/
if (introductionAwareMethodMatcher != null ?
introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) :
methodMatcher.matches(method, targetClass)) {
return true;
}
}
}
return false;
}
//省略其它抽象...
}
public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {
@Override
/*xxx: 前置处理前,就会进行动态代理类的分流*/
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
/*xxx:拿到 特定名称 和 特定类,组成key,标识一个唯一bean*/
Object cacheKey = getCacheKey(beanClass, beanName);
if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
/*xxx: 如果已经生成了代理对象,则跳过 */
if (this.advisedBeans.containsKey(cacheKey)) {
return null;
}
/*xxx: 如果该bean是 Advice,Pointcut,Advisor,AopInfrastructureBean的子类,或者 这个bean是源实例,则记录该bean的情况*/
/*xxx: 即,动态代理类的配置类本身,是不需要被代理的*/
if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
}
// Create proxy here if we have a custom TargetSource.
// Suppresses unnecessary default instantiation of the target bean:
// The TargetSource will handle target instances in a custom fashion.
/*xxx: 根据是否有 TargetSource,来决定是否代理*/
TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
if (targetSource != null) {
if (StringUtils.hasLength(beanName)) {
this.targetSourcedBeans.add(beanName);
}
/*xxx:获取当前bean的 切面通知和通知器,通过子类完成 */
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
/*xxx:记录已经创建了的代理对象 */
this.proxyTypes.put(cacheKey, proxy.getClass());
/*xxx: 然后将 生成的代理对象,返回给工厂,这就起到了移花接木的作用*/
return proxy;
}
return null;
}
@Override
/*xxx: 正常情况下,都是通过初始化后置方法来完成动态代理的。 当前,实例化前置方法也可完成动态代理,是根据名称来进行判定是否需要代理的*/
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
/*xxx: 某个bean 已经实例化后*/
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
/*xxx: 由于 智能实例化 处理了 循环引用的情况,这里需要在bean实例化后,继续解决是否需要自动生成代理的情况*/
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
/*xxx: 通常情况下的动态代理 */
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
return bean;
}
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
return bean;
}
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
// Create proxy if we have advice.
/*xxx: 为指定类,获取匹配的 拦截切面,获取到则进行代理,否则不进行代理,在aop的环境,所有的类都会经历这个过程*/
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
Object proxy = createProxy(
bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
/*xxx: 创建实际的动态代理类 */
protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
@Nullable Object[] specificInterceptors, TargetSource targetSource) {
if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
}
/*xxx: 创建代理工厂*/
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.copyFrom(this);
if (!proxyFactory.isProxyTargetClass()) {
if (shouldProxyTargetClass(beanClass, beanName)) {
proxyFactory.setProxyTargetClass(true);
}
else {
evaluateProxyInterfaces(beanClass, proxyFactory);
}
}
Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
proxyFactory.addAdvisors(advisors);
proxyFactory.setTargetSource(targetSource);
customizeProxyFactory(proxyFactory);
proxyFactory.setFrozen(this.freezeProxy);
if (advisorsPreFiltered()) {
proxyFactory.setPreFiltered(true);
}
return proxyFactory.getProxy(getProxyClassLoader());
}
}
- 自动代理注解的处理解析
public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator {
@Override
protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
super.initBeanFactory(beanFactory);
if (this.aspectJAdvisorFactory == null) {
/*xxx: 实例化 反射切面Aspectj通知器工厂*/
this.aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory);
}
/*xxx: 实例化 aspecjt通知器构造器,用于解析动态代理注解*/
this.aspectJAdvisorsBuilder =
new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this.aspectJAdvisorFactory);
}
@Override
protected List<Advisor> findCandidateAdvisors() {
// Add all the Spring advisors found according to superclass rules.
List<Advisor> advisors = super.findCandidateAdvisors();
// Build Advisors for all AspectJ aspects in the bean factory.
if (this.aspectJAdvisorsBuilder != null) {
advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
}
return advisors;
}
//省略其它抽象
}
private class BeanFactoryAspectJAdvisorsBuilderAdapter extends BeanFactoryAspectJAdvisorsBuilder {
public BeanFactoryAspectJAdvisorsBuilderAdapter(
ListableBeanFactory beanFactory, AspectJAdvisorFactory advisorFactory) {
super(beanFactory, advisorFactory);
}
@Override
protected boolean isEligibleBean(String beanName) {
return AnnotationAwareAspectJAutoProxyCreator.this.isEligibleAspectBean(beanName);
}
}
public class BeanFactoryAspectJAdvisorsBuilder {
/*xxx: 构建通知器列表 */
public List<Advisor> buildAspectJAdvisors() {
List<String> aspectNames = this.aspectBeanNames;
if (aspectNames == null) {
synchronized (this) {
aspectNames = this.aspectBeanNames;
if (aspectNames == null) {
List<Advisor> advisors = new ArrayList<>();
aspectNames = new ArrayList<>();
String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.beanFactory, Object.class, true, false);
for (String beanName : beanNames) {
if (!isEligibleBean(beanName)) {
continue;
}
// We must be careful not to instantiate beans eagerly as in this case they
// would be cached by the Spring container but would not have been weaved.
Class<?> beanType = this.beanFactory.getType(beanName, false);
if (beanType == null) {
continue;
}
/*xxx: 如果bean,被 @Aspect注解, 则是切面通知器 */
if (this.advisorFactory.isAspect(beanType)) {
aspectNames.add(beanName);
AspectMetadata amd = new AspectMetadata(beanType, beanName);
if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
MetadataAwareAspectInstanceFactory factory =
new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory);
if (this.beanFactory.isSingleton(beanName)) {
this.advisorsCache.put(beanName, classAdvisors);
}
else {
this.aspectFactoryCache.put(beanName, factory);
}
advisors.addAll(classAdvisors);
}
else {
// Per target or per this.
/*xxx: 原型模式的通知器 */
if (this.beanFactory.isSingleton(beanName)) {
throw new IllegalArgumentException("Bean with name '" + beanName +
"' is a singleton, but aspect instantiation model is not singleton");
}
MetadataAwareAspectInstanceFactory factory =
new PrototypeAspectInstanceFactory(this.beanFactory, beanName);
this.aspectFactoryCache.put(beanName, factory);
advisors.addAll(this.advisorFactory.getAdvisors(factory));
}
}
}
this.aspectBeanNames = aspectNames;
return advisors;
}
}
}
if (aspectNames.isEmpty()) {
return Collections.emptyList();
}
List<Advisor> advisors = new ArrayList<>();
for (String aspectName : aspectNames) {
List<Advisor> cachedAdvisors = this.advisorsCache.get(aspectName);
if (cachedAdvisors != null) {
advisors.addAll(cachedAdvisors);
}
else {
MetadataAwareAspectInstanceFactory factory = this.aspectFactoryCache.get(aspectName);
advisors.addAll(this.advisorFactory.getAdvisors(factory));
}
}
return advisors;
}
//省略其它抽象...
}
public interface AspectJAdvisorFactory {
boolean isAspect(Class<?> clazz);
List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory);
//省略其它抽象...
}
public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFactory implements Serializable {
@Override
/*xxx: 判断是否是切点*/
public boolean isAspect(Class<?> clazz) {
return (hasAspectAnnotation(clazz) && !compiledByAjc(clazz));
}
private boolean hasAspectAnnotation(Class<?> clazz) {
return (AnnotationUtils.findAnnotation(clazz, Aspect.class) != null);
}
@Override
/*xxx: 构建通知器*/
public List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) {
Class<?> aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();
validate(aspectClass);
MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =
new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);
List<Advisor> advisors = new ArrayList<>();
for (Method method : getAdvisorMethods(aspectClass)) {
/*xxx: 遍历方法,并处理成 advisor */
Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, 0, aspectName);
if (advisor != null) {
advisors.add(advisor);
}
}
// If it's a per target aspect, emit the dummy instantiating aspect.
if (!advisors.isEmpty() && lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {
Advisor instantiationAdvisor = new SyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory);
advisors.add(0, instantiationAdvisor);
}
// Find introduction fields.
for (Field field : aspectClass.getDeclaredFields()) {
Advisor advisor = getDeclareParentsAdvisor(field);
if (advisor != null) {
advisors.add(advisor);
}
}
return advisors;
}
/*xxx: 获取通知器方法 */
private List<Method> getAdvisorMethods(Class<?> aspectClass) {
final List<Method> methods = new ArrayList<>();
ReflectionUtils.doWithMethods(aspectClass, method -> {
// Exclude pointcuts
/*xxx: 具有 @Pointcut的方法需要被排除 */
if (AnnotationUtils.getAnnotation(method, Pointcut.class) == null) {
methods.add(method);
}
}, ReflectionUtils.USER_DECLARED_METHODS);
if (methods.size() > 1) {
methods.sort(METHOD_COMPARATOR);
}
return methods;
}
@Override
@Nullable
public Advisor getAdvisor(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aspectInstanceFactory,
int declarationOrderInAspect, String aspectName) {
validate(aspectInstanceFactory.getAspectMetadata().getAspectClass());
/*xxx: 获取切点表达式,如果具有切点表达式,才算合法的 通知器,否则不合法 */
AspectJExpressionPointcut expressionPointcut = getPointcut(
candidateAdviceMethod, aspectInstanceFactory.getAspectMetadata().getAspectClass());
if (expressionPointcut == null) {
return null;
}
return new InstantiationModelAwarePointcutAdvisorImpl(expressionPointcut, candidateAdviceMethod,
this, aspectInstanceFactory, declarationOrderInAspect, aspectName);
}
}
# aop联盟切面编程的定义

- 说明:
- Advice,在springAop环境中,可以理解为 拦截器, 它通常与 PointCut联合使用
- PointCut可以理解为 切点表达式
# Spring框架实现的切面代理
# cache缓存
- api使用说明
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
/*xxx: 放入缓存 */
public @interface CachePut {
String key() default "";
String keyGenerator() default "";
String cacheManager() default "";
//xxx:省略其它抽象...
}
@Target({ElementType.TYPE, ElementType.METHOD})
/*xxx: 允许缓存注解,使 被注解对象,成为 代理对象*/
public @interface Cacheable {
@AliasFor("value")
String[] cacheNames() default {};
String key() default "";
String cacheManager() default "";
/*xxx: 这里可以配置 缓存命中的表达式 默认总是命中缓存*/
String condition() default "";
}
/*xxx: 类级别的缓存默认配置*/
@Target(ElementType.TYPE)
public @interface CacheConfig {
//xxx: 省略其它抽象...
}
@Target({ElementType.TYPE, ElementType.METHOD})
/*xxx: 缓存evict操作,移除操作*/
public @interface CacheEvict {
//xxx: 省略其它抽象...
}
@Import(CachingConfigurationSelector.class)
/*xxx: 开启缓存注解*/
public @interface EnableCaching {
/*xxx: 切面代理模式*/
AdviceMode mode() default AdviceMode.PROXY;
/*xxx: 省略其它抽象...*/
}
- 实现原理
@Import(CachingConfigurationSelector.class)
/*xxx: 缓存注解*/
public @interface EnableCaching {
/*xxx: 切面代理模式*/
AdviceMode mode() default AdviceMode.PROXY;
/*xxx: 省略其它抽象...*/
}
/*xxx: 缓存机制 bean 引入配置 */
public class CachingConfigurationSelector extends AdviceModeImportSelector<EnableCaching> {
@Override
/*xxx: 根据注解配置的模式,决定引入的切面类 */
public String[] selectImports(AdviceMode adviceMode) {
switch (adviceMode) {
case PROXY:
/*xxx: 默认值*/
return getProxyImports();
case ASPECTJ:
return getAspectJImports();
default:
return null;
}
}
private String[] getProxyImports() {
List<String> result = new ArrayList<>(3);
result.add(AutoProxyRegistrar.class.getName());
result.add(ProxyCachingConfiguration.class.getName());
if (jsr107Present && jcacheImplPresent) {
result.add(PROXY_JCACHE_CONFIGURATION_CLASS);
}
/*xxx: 此种模式,引入三个类,分别为: */
/*xxx: org.springframework.context.annotation.AutoProxyRegistrar*/
/*xxx: org.springframework.cache.annotation.ProxyCachingConfiguration*/
/*xxx: org.springframework.cache.jcache.config.ProxyJCacheConfiguration*/
return StringUtils.toStringArray(result);
}
//xxx: 省略其它抽象...
}
/*xxx: 自动代理注册器, 后续创建代理类,需要依赖此类*/
/*xxx: 进行了上下文判断,如果已有该基础设施,则不再进行创建 */
public class AutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
//xxx: 省略其它抽象...
AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
}
}
@Configuration(proxyBeanMethods = false)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
/*xxx: 缓存基础设施配置 */
public class ProxyCachingConfiguration extends AbstractCachingConfiguration {
@Bean(name = CacheManagementConfigUtils.CACHE_ADVISOR_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
/*xxx: 缓存切面*/
public BeanFactoryCacheOperationSourceAdvisor cacheAdvisor(
CacheOperationSource cacheOperationSource, CacheInterceptor cacheInterceptor) {
BeanFactoryCacheOperationSourceAdvisor advisor = new BeanFactoryCacheOperationSourceAdvisor();
advisor.setCacheOperationSource(cacheOperationSource);
advisor.setAdvice(cacheInterceptor);
if (this.enableCaching != null) {
advisor.setOrder(this.enableCaching.<Integer>getNumber("order"));
}
return advisor;
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
/*xxx: 缓存操作源*/
public CacheOperationSource cacheOperationSource() {
return new AnnotationCacheOperationSource();
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
/*xxx: 缓存拦截器 */
public CacheInterceptor cacheInterceptor(CacheOperationSource cacheOperationSource) {
CacheInterceptor interceptor = new CacheInterceptor();
interceptor.configure(this.errorHandler, this.keyGenerator, this.cacheResolver, this.cacheManager);
interceptor.setCacheOperationSource(cacheOperationSource);
return interceptor;
}
}
/*xxx: 缓存拦截器,最终作为一个 方法连接点 参与切面 */
public class CacheInterceptor extends CacheAspectSupport implements MethodInterceptor, Serializable {
@Override
@Nullable
/*xxx: 缓存代理对象执行的方法 */
public Object invoke(final MethodInvocation invocation) throws Throwable {
/*xxx: 包装方法,用于向后执行*/
CacheOperationInvoker aopAllianceInvoker = () -> {
try {
return invocation.proceed();
}
catch (Throwable ex) {
throw new CacheOperationInvoker.ThrowableWrapper(ex);
}
};
return execute(aopAllianceInvoker, target, method, invocation.getArguments());
//xxx: 省略其它抽象...
}
}
public abstract class CacheAspectSupport extends AbstractCacheInvoker
implements BeanFactoryAware, InitializingBean, SmartInitializingSingleton {
@Nullable
protected Object execute(CacheOperationInvoker invoker, Object target, Method method, Object[] args) {
/*xxx: 缓存操作源 */
CacheOperationSource cacheOperationSource = getCacheOperationSource();
if (cacheOperationSource != null) {
/*xxx: 通过切面的操作,执行缓存操作*/
Collection<CacheOperation> operations = cacheOperationSource.getCacheOperations(method, targetClass);
if (!CollectionUtils.isEmpty(operations)) {
/*xxx: 执行缓存操作 */
return execute(invoker, method,
new CacheOperationContexts(operations, method, args, target, targetClass));
}
}
//xxx: 省略其它抽象...
}
@Nullable
/*xxx: 执行缓存操作 */
private Object execute(final CacheOperationInvoker invoker, Method method, CacheOperationContexts contexts) {
/*xxx: 缓存命中条件 */
Cache.ValueWrapper cacheHit = findCachedItem(contexts.get(CacheableOperation.class));
Object cacheValue;
Object returnValue;
if (cacheHit != null && !hasCachePut(contexts)) {
// If there are no put requests, just use the cache hit
cacheValue = cacheHit.get();
/*xxx: 命中缓存,则直接返回缓存值*/
returnValue = wrapCacheValue(method, cacheValue);
}
else {
// Invoke the method if we don't have a cache hit
/*xxx: 没有命中缓存值,则正常执行方法,并将返回值缓存*/
returnValue = invokeOperation(invoker);
cacheValue = unwrapReturnValue(returnValue);
}
//xxx: 省略其它抽象...
//xxx: 此外,还处理了 @CachePut,CacheEvict 缓存造作
return returnValue;
}
}
/*xxx: 缓存切面*/
public class BeanFactoryCacheOperationSourceAdvisor extends AbstractBeanFactoryPointcutAdvisor {
/*xxx: 缓存代理 切入点*/
private final CacheOperationSourcePointcut pointcut = new CacheOperationSourcePointcut() {
@Override
@Nullable
protected CacheOperationSource getCacheOperationSource() {
return cacheOperationSource;
}
};
@Override
public Pointcut getPointcut() {
return this.pointcut;
}
}
/*xxx: 缓存切入点 */
abstract class CacheOperationSourcePointcut extends StaticMethodMatcherPointcut implements Serializable {
@Override
/*xxx: 代理的条件为: 缓存操作源存在,且 当前要检查的对象存在 缓存操作,包括: 获取缓存,新增缓存,移除缓存,缓存分组四个注解*/
/*xxx: 对于 @Caching @CachePut @CacheEvict @Cacheable 进行增强*/
public boolean matches(Method method, Class<?> targetClass) {
CacheOperationSource cas = getCacheOperationSource();
return (cas != null && !CollectionUtils.isEmpty(cas.getCacheOperations(method, targetClass)));
}
}
# transactional事务
- api说明
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
/*xxx: 事务注解 */
public @interface Transactional {
@AliasFor("value")
/*xxx: 事务管理器 */
String transactionManager() default "";
/*xxx: 事务传播特性*/
Propagation propagation() default Propagation.REQUIRED;
/*xxx: 事务隔离级别*/
Isolation isolation() default Isolation.DEFAULT;
/*xxx: 事务超时时间 */
int timeout() default TransactionDefinition.TIMEOUT_DEFAULT;
/*xxx: 只读事务*/
boolean readOnly() default false;
/*xxx: 默认情况下,非受检异常 会回滚*/
Class<? extends Throwable>[] rollbackFor() default {};
}
- 原理
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(TransactionManagementConfigurationSelector.class)
/*xxx: 允许事务特性*/
public @interface EnableTransactionManagement {
/*xxx: 代理模式 */
AdviceMode mode() default AdviceMode.PROXY;
}
/*xxx: 事务管理引入bean配置 */
public class TransactionManagementConfigurationSelector extends AdviceModeImportSelector<EnableTransactionManagement> {
@Override
protected String[] selectImports(AdviceMode adviceMode) {
switch (adviceMode) {
case PROXY:
/*xxx: 默认值 */
return new String[] {AutoProxyRegistrar.class.getName(),
ProxyTransactionManagementConfiguration.class.getName()};
case ASPECTJ:
return new String[] {determineTransactionAspectClass()};
default:
return null;
}
}
//xxx: 省略其它抽象...
}
@Configuration(proxyBeanMethods = false)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
/*xxx: 事务代理配置 */
public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {
@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
/*xxx: 事务切面*/
public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor(
TransactionAttributeSource transactionAttributeSource, TransactionInterceptor transactionInterceptor) {
BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
advisor.setTransactionAttributeSource(transactionAttributeSource);
advisor.setAdvice(transactionInterceptor);
if (this.enableTx != null) {
advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
}
return advisor;
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
/*xxx: 事务属性源*/
public TransactionAttributeSource transactionAttributeSource() {
return new AnnotationTransactionAttributeSource();
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
/*xxx: 事务拦截器 */
public TransactionInterceptor transactionInterceptor(TransactionAttributeSource transactionAttributeSource) {
TransactionInterceptor interceptor = new TransactionInterceptor();
interceptor.setTransactionAttributeSource(transactionAttributeSource);
if (this.txManager != null) {
interceptor.setTransactionManager(this.txManager);
}
return interceptor;
}
}
/*xxx: 事务拦截器 */
public class TransactionInterceptor extends TransactionAspectSupport implements MethodInterceptor, Serializable {
@Override
@Nullable
/*xxx: 事务拦截器 执行的方法 */
public Object invoke(MethodInvocation invocation) throws Throwable {
Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
return invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed);
}
}
public abstract class TransactionAspectSupport implements BeanFactoryAware, InitializingBean {
@Override
public void afterPropertiesSet() {
/*xxx: 事务管理器 是跟 数据源挂钩的,属于jdbc, 事务最开始也源于 数据库领域, 所以事务管理器是必备的*/
//xxx: 省略其它抽象...
}
@Nullable
/*xxx: 事务内执行 */
protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass,
final InvocationCallback invocation) throws Throwable {
/*xxx: 获取事务管理器 */
final TransactionManager tm = determineTransactionManager(txAttr);
//xxx: 省略其它抽象...
/*xxx: 新建事务信息, 会将其保存至线程上下文中 ,通过bindToThread()方法*/
/*xxx: 新建事务信息,会进行 事务状态的传递 */
/*xxx: 相当于 开启事务*/
TransactionInfo txInfo = createTransactionIfNecessary(ptm, txAttr, joinpointIdentification);
/*xxx: 返回值*/
Object retVal;
try {
/*xxx: 执行业务方法*/
retVal = invocation.proceedWithInvocation();
}catch (Throwable ex) {
/*xxx: 业务方法执行报错,回滚*/
completeTransactionAfterThrowing(txInfo, ex);
throw ex;
}finally {
/*xxx: 清除当前事务*/
/*xxx: 类似于 当前事务出栈*/
cleanupTransactionInfo(txInfo);
}
/*xxx: 提交事务*/
commitTransactionAfterReturning(txInfo);
/*xxx: 如果方法正常执行,则必提交事务成功*/
return retVal;
}
/*xxx: 获取缓存操作上下文*/
protected CacheOperationContext getOperationContext(
CacheOperation operation, Method method, Object[] args, Object target, Class<?> targetClass) {
/*xxx: 获取缓存操作元数据 信息*/
CacheOperationMetadata metadata = getCacheOperationMetadata(operation, method, targetClass);
return new CacheOperationContext(metadata, args, target);
}
/*xxx: 获取缓存操作元数据*/
protected CacheOperationMetadata getCacheOperationMetadata(
CacheOperation operation, Method method, Class<?> targetClass) {
/*xxx: 获取缓存键*/
CacheOperationCacheKey cacheKey = new CacheOperationCacheKey(operation, method, targetClass);
/*xxx: 从缓存中获取元数据,没有则进行解析*/
CacheOperationMetadata metadata = this.metadataCache.get(cacheKey);
if (metadata == null) {
KeyGenerator operationKeyGenerator;
/*xxx: 键名生成器, 如果指定了就用指定的*/
if (StringUtils.hasText(operation.getKeyGenerator())) {
/*xxx: 从上下文中,获取键名生成器*/
operationKeyGenerator = getBean(operation.getKeyGenerator(), KeyGenerator.class);
}
else {
/*xxx: 没指定就用默认的 为SimpleKeyGenerator */
operationKeyGenerator = getKeyGenerator();
}
CacheResolver operationCacheResolver;
/*xxx: 如果配置了缓存解析器,则从上下文中获取缓存解析器*/
if (StringUtils.hasText(operation.getCacheResolver())) {
/*xxx: 从上下文中,获取缓存解析器*/
operationCacheResolver = getBean(operation.getCacheResolver(), CacheResolver.class);
}
/*xxx: 如果配置了 缓存管理器,则从上下文中获取缓存管理器*/
else if (StringUtils.hasText(operation.getCacheManager())) {
/*xxx: 从上下文中获取缓存管理器,并将其封装为 缓存解析器进行返回*/
CacheManager cacheManager = getBean(operation.getCacheManager(), CacheManager.class);
operationCacheResolver = new SimpleCacheResolver(cacheManager);
}
//xxx: 使用cache时, CacheResolver 与 CacheManager至少具备一个环境, cacheResolver本质上也是CacheManager
else {
operationCacheResolver = getCacheResolver();
Assert.state(operationCacheResolver != null, "No CacheResolver/CacheManager set");
}
metadata = new CacheOperationMetadata(operation, method, targetClass,
operationKeyGenerator, operationCacheResolver);
this.metadataCache.put(cacheKey, metadata);
}
return metadata;
}
private class CacheOperationContexts {
//xxx: 存储缓存相关操作
private final MultiValueMap<Class<? extends CacheOperation>, CacheOperationContext> contexts;
/*xxx: 缓存上下文*/
public CacheOperationContexts(Collection<? extends CacheOperation> operations, Method method,
Object[] args, Object target, Class<?> targetClass) {
this.contexts = new LinkedMultiValueMap<>(operations.size());
for (CacheOperation op : operations) {
this.contexts.add(op.getClass(), getOperationContext(op, method, args, target, targetClass));
}
}
}
}
/*xxx: 事务切面*/
public class BeanFactoryTransactionAttributeSourceAdvisor extends AbstractBeanFactoryPointcutAdvisor {
private final TransactionAttributeSourcePointcut pointcut = new TransactionAttributeSourcePointcut() {
@Override
@Nullable
protected TransactionAttributeSource getTransactionAttributeSource() {
return transactionAttributeSource;
}
};
@Override
public Pointcut getPointcut() {
return this.pointcut;
}
}
/*xxx: 事务切点*/
abstract class TransactionAttributeSourcePointcut extends StaticMethodMatcherPointcut implements Serializable {
@Override
/*xxx: 类名,或者方法名 带有 @Transactional注解,将会被增强*/
public boolean matches(Method method, Class<?> targetClass) {
TransactionAttributeSource tas = getTransactionAttributeSource();
return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
}
}
# schedule调度
- 原理
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
/*xxx: 调度功能,注解在方法上 */
public @interface Scheduled {
/*xxx: 调度表达式 */
String cron() default "";
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(SchedulingConfiguration.class)
@Documented
/*xxx: 开启调度特性*/
public @interface EnableScheduling {
}
@Configuration(proxyBeanMethods = false)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
/*xxx: 调度配置 */
public class SchedulingConfiguration {
@Bean(name = TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
/*xxx: 注入 调度注解的 bean后置处理器*/
public ScheduledAnnotationBeanPostProcessor scheduledAnnotationProcessor() {
return new ScheduledAnnotationBeanPostProcessor();
}
}
/*xxx: 调度注解 bean后置处理器 */
public class ScheduledAnnotationBeanPostProcessor
implements ScheduledTaskHolder, MergedBeanDefinitionPostProcessor, DestructionAwareBeanPostProcessor,
Ordered, EmbeddedValueResolverAware, BeanNameAware, BeanFactoryAware, ApplicationContextAware,
SmartInitializingSingleton, ApplicationListener<ContextRefreshedEvent>, DisposableBean {
/*xxx: 调度注解 bean后置处理器 */
public class ScheduledAnnotationBeanPostProcessor
implements ScheduledTaskHolder, MergedBeanDefinitionPostProcessor, DestructionAwareBeanPostProcessor,
Ordered, EmbeddedValueResolverAware, BeanNameAware, BeanFactoryAware, ApplicationContextAware,
SmartInitializingSingleton, ApplicationListener<ContextRefreshedEvent>, DisposableBean {
@Override
/*xxx: bean后置处理器,在bean初始化完毕后执行 */
public Object postProcessAfterInitialization(Object bean, String beanName) {
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
/*xxx: 对每个bean都进行注解检查,*/
if (!this.nonAnnotatedClasses.contains(targetClass) &&
AnnotationUtils.isCandidateClass(targetClass, Arrays.asList(Scheduled.class, Schedules.class))) {
/*xxx: 查找 调度注解,如果没找到,则记录下来,下一次不再判断*/
if (annotatedMethods.isEmpty()) {
this.nonAnnotatedClasses.add(targetClass);
}else {
/*xxx: 如果找到了注解,则进行处理,每个注解都会对应一个方法 */
/*xxx: 一个方法可能有多个注解 */
annotatedMethods.forEach((method, scheduledMethods) ->
/*xxx: 对调度方法进行处理 */
scheduledMethods.forEach(scheduled -> processScheduled(scheduled, method, bean)));
}
}
}
/*xxx: 处理调度(新建调度任务,并参与调度 )*/
protected void processScheduled(Scheduled scheduled, Method method, Object bean) {
/*xxx: 通过反射,构造执行任务*/
Runnable runnable = createRunnable(bean, method);
/*xxx: 构造cron任务,并参与调度。*/
/*xxx: 调度可通过 ScheduleExecutorService */
tasks.add(this.registrar.scheduleCronTask(new CronTask(runnable, new CronTrigger(cron, timeZone))));
/*xxx: 最后将任务放入任务池进行存根 */
synchronized (this.scheduledTasks) {
Set<ScheduledTask> regTasks = this.scheduledTasks.computeIfAbsent(bean, key -> new LinkedHashSet<>(4));
regTasks.addAll(tasks);
}
//xxx: 省略其它抽象...
}
}
}