Spring源码学习笔记(9)——AOP
一. 基于注解的AOP开发
AOP的定义及一些术语相信大家已经很熟悉了,这里不再赘述。下面演示基于注解的Spring AOP开发。
- 编写业务逻辑类
@Component
public class SimpleCalculator {
int divide(int x,int y){
return x / y;
}
}
- 编写了一个简单的计算器类,计算整数的除法。
- 编写切面类,并指定通知类型和切入点
@Aspect
@Component
public class CalculatorAspect {
//声明切入点
@Pointcut("execution(public * william.annotation.component.SimpleCalculator.*(..))")
public void pointcut(){}
//前置通知
@Before("pointcut()")
public void before(JoinPoint joinPoint){
System.err.println("前置通知-->方法名: " joinPoint.getSignature().getName()
",参数列表: " Arrays.asList(joinPoint.getArgs()));
}
//后置通知
@AfterReturning(value = "pointcut()",returning = "retVal")
public void after(JoinPoint joinPoint,Object retVal){
System.err.println("后置通知-->方法名: " joinPoint.getSignature().getName()
",返回值: " retVal);
}
//环绕通知
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
System.err.println("环绕通知前-->方法名: " joinPoint.getSignature().getName());
Object retVal = joinPoint.proceed();
System.err.println("环绕通知后-->返回值: " retVal);
return retVal;
}
}
- 使用@Aspect注解声明一个切面。切面包含切入点和通知方法。使用@Pointcut注解可以以方法的方式声明切入点,切入点表达式的相关内容这里不做过多介绍。使用@Before、@After、@Around等注解可以声明前置、后置、增强通知等。
- 开启基于注解的AOP功能
@Configuration
@ComponentScan
@EnableAspectJAutoProxy
public class MainConfig {
}
- 在配置类上使用@EnableAspectJAutoProxy注解开启AOP自动代理,Spring就可以根据上述注解自动实现AOP的功能。 执行测试代码,观察控制台打印:
public class AnnotationMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
SimpleCalculator simpleCalculator = applicationContext.getBean(SimpleCalculator.class);
simpleCalculator.divide(1,1);
}
}
代码语言:javascript复制环绕通知前-->方法名: divide
前置通知-->方法名: divide,参数列表: [1, 1]
环绕通知后-->返回值: 1
后置通知-->方法名: divide,返回值: 1
二. AOP源码分析
在上面的实例中,使用@EnableAspectJAutoProxy注解就可以开启自动代理功能,那么该功能是如何实现的呢?首先看@EnableAspectJAutoProxy源码:
代码语言:javascript复制@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {
//是否强制使用CGLib进行动态代理
boolean proxyTargetClass() default false;
}
可以看到,@EnableAspectJAutoProxy注解使用@Import导入了一个AspectJAutoProxyRegistrar类,@Import的功能在前面有过详细介绍,下面看AspectJAutoProxyRegistrar:
代码语言:javascript复制class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(
AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
AnnotationAttributes enableAJAutoProxy =
AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
if (enableAJAutoProxy.getBoolean("proxyTargetClass")) {
AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
}
}
}
核心逻辑在AopConfigUtils.registerOrEscalateApcAsRequired()方法中:
代码语言:javascript复制private static BeanDefinition registerOrEscalateApcAsRequired(Class<?> cls, BeanDefinitionRegistry registry, Object source) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
if (!cls.getName().equals(apcDefinition.getBeanClassName())) {
int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());
int requiredPriority = findPriorityForClass(cls);
if (currentPriority < requiredPriority) {
apcDefinition.setBeanClassName(cls.getName());
}
}
return null;
}
//向容器中注册一个beanName为org.springframework.aop.config.internalAutoProxyCreator的Bean:AnnotationAwareAspectJAutoProxyCreator
RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
beanDefinition.setSource(source);
beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);
beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);
return beanDefinition;
}
该方法首先检查容器中是否已经存在beanName为org.springframework.aop.config.internalAutoProxyCreator的Bean,如果没有,则以该beanName注册一个Bean:AnnotationAwareAspectJAutoProxyCreator。AnnotationAwareAspectJAutoProxyCreator是Spring AOP的一个重要组件,下面对其进行分析:
先简单看一下AnnotationAwareAspectJAutoProxyCreator的继承路径:
AnnotationAwareAspectJAutoProxyCreator—>AspectJAwareAdvisorAutoProxyCreator—>AbstractAdvisorAutoProxyCreator—>AbstractAutoProxyCreator,而AbstractAutoProxyCreator实现了SmartInstantiationAwareBeanPostProcessor和BeanFactoryAware接口,这也就意味着AnnotationAwareAspectJAutoProxyCreator具有后处理器和BeanFactoryAware接口的功能,这也是Spring处理AOP动态代理的地方。
首先看AbstractAutoProxyCreator的后处理方法:
SmartInstantiationAwareBeanPostProcessor是一种特殊的后处理器,可以它不是在Bean的属性赋值前后进行拦截,而是在Bean实例化前后进行拦截,由此可以将一个Bean转换成代理的Bean。
代码语言:javascript复制public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (!this.earlyProxyReferences.contains(cacheKey)) {
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
首先在代理缓存池中查看当前beanName是否已经创建了代理对象,如果已经创建,则直接返回代理对象,否则执行创建代理对象的逻辑,即wrapIfNecessary()方法:
代码语言:javascript复制protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (beanName != null && 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;
}
//获取基于bean的所有拦截器,组成一个拦截器链,并根据拦截器链创建代理对象
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;
}
创建代理对象的处理在createProxy()方法中:
代码语言:javascript复制protected Object createProxy(
Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {
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);
for (Advisor advisor : advisors) {
proxyFactory.addAdvisor(advisor);
}
proxyFactory.setTargetSource(targetSource);
customizeProxyFactory(proxyFactory);
proxyFactory.setFrozen(this.freezeProxy);
if (advisorsPreFiltered()) {
proxyFactory.setPreFiltered(true);
}
return proxyFactory.getProxy(getProxyClassLoader());
}