Spring的AOP组件详解

简介: 该文章主要介绍了Spring AOP(面向切面编程)组件的实现原理,包括Spring AOP的基础概念、动态代理模式、AOP组件的实现以及Spring选择JDK动态代理或CGLIB动态代理的依据。

前言

Spring AOP是基于动态代理模式实现的面向切面编程,非常方便和Spring的组件集成,并且在Spring环境中开发切面功能代码。

动态代理知识回顾

先回忆一下动态代理的知识:

image.png

Spring在选择用JDK还是CGLib的依据

当Bean实现接口时,Spring就会用JDK的动态代理 当Bean没有实现接口时,Spring使用CGLib来实现 可以强制使用CGLib(在Spring配置中加入)

Spring Aop元数据解析

Spring中Aop是怎么基于动态代理实现的?

首先要找到入口,在spring di的时候,bean初始化前后会触发后置处理的回调函数执行。

在下面的AbstractAutowireCapableBeanFactory工厂类中看到bean初始化流程:


//具有自动依赖注入的的bean工厂

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory

implements AutowireCapableBeanFactory {
   
   

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)

throws BeanCreationException {
   
   

// Instantiate the bean.创建bean

BeanWrapper instanceWrapper = createBeanInstance(beanName, mbd, args);

// Initialize the bean instance.

Object exposedObject = bean;

//填充属性

populateBean(beanName, mbd, instanceWrapper);

//触发初始化方法

exposedObject = initializeBean(beanName, exposedObject, mbd);

}

// ....

return exposedObject;

}

//初始化方法

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
   
   

//触发感知赋值spring的基础设施bean

invokeAwareMethods(beanName, bean);

Object wrappedBean = bean;

if (mbd == null || !mbd.isSynthetic()) {
   
   

//应用beanpostprocessor的初始化前回调方法

wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);

}

try {
   
   

//调用初始化方法

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()) {
   
   

//应用beanpostprocessor的初始化后回调方法

wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);

}

return wrappedBean;

}

@Override

public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)

throws BeansException {
   
   

Object result = existingBean;

//应用所有beanpostprocessor的初始化前回调方法

for (BeanPostProcessor processor : getBeanPostProcessors()) {
   
   

Object current = processor.postProcessBeforeInitialization(result, beanName);

if (current == null) {
   
   

return result;

}

result = current;

}

return result;

}

@Override

public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)

throws BeansException {
   
   

Object result = existingBean;

for (BeanPostProcessor processor : getBeanPostProcessors()) {
   
   

//应用所有beanpostprocessor的初始化后回调方法

Object current = processor.postProcessAfterInitialization(result, beanName);

if (current == null) {
   
   

return result;

}

result = current;

}

return result;

}

image.png

通过类结构图可知AbstractAutoProxyCreator是Spring Aop模块实现了BeanPostProcessor接口的实现类。

image.png

继续跟进AbstractAutoProxyCreator的postProcessAfterInitialization方法


@Override

public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
   
   

if (bean != null) {
   
   

//缓存

Object cacheKey = getCacheKey(bean.getClass(), beanName);

if (this.earlyProxyReferences.remove(cacheKey) != bean) {
   
   

//这个地方可能返回代理

return wrapIfNecessary(bean, beanName, cacheKey);

}

}

return bean;

}

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.

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;

}

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);

}

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 DefaultAopProxyFactory implements AopProxyFactory, Serializable {
   
   

//有两种选择,一个是jdk动态代理,一个是cglib,

@Override

public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
   
   

if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
   
   

Class<?> targetClass = config.getTargetClass();

if (targetClass == null) {
   
   

throw new AopConfigException("TargetSource cannot determine target class: " +

"Either an interface or a target is required for proxy creation.");

}

if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
   
   

//jdk代理

return new JdkDynamicAopProxy(config);

}

//cglib

return new ObjenesisCglibAopProxy(config);

}

else {
   
   

//jdk代码

return new JdkDynamicAopProxy(config);

}

}

/**

* Determine whether the supplied {@link AdvisedSupport} has only the

* {@link org.springframework.aop.SpringProxy} interface specified

* (or no proxy interfaces specified at all).

*/

private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
   
   

Class<?>[] ifcs = config.getProxiedInterfaces();

return (ifcs.length == 0 || (ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0])));

}

}

Spring Aop调用流程

//jdk的代理创建好了,调用过程是怎么样的了?

JdkDynamicAopProxy实现了InvocationHandler接口,里面实现了invoke方法,这个方法实现就是代理执行逻辑。


@Override

@Nullable

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   
   

Object oldProxy = null;

boolean setProxyContext = false;

TargetSource targetSource = this.advised.targetSource;

Object target = null;

try {
   
   

//判断是否是Object类的一些方法

if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
   
   

// The target does not implement the equals(Object) method itself.

return equals(args[0]);

}

else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
   
   

// The target does not implement the hashCode() method itself.

return hashCode();

}

else if (method.getDeclaringClass() == DecoratingProxy.class) {
   
   

// There is only getDecoratedClass() declared -> dispatch to proxy config.

return AopProxyUtils.ultimateTargetClass(this.advised);

}

//判断是否是Advised的实现类,如果是不走拦截器

else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&

method.getDeclaringClass().isAssignableFrom(Advised.class)) {
   
   

// Service invocations on ProxyConfig with the proxy config...

//反射调用

return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);

}

Object retVal;

//这里是spring提供暴露代理对象的口子,通过设置exposeProxy为true,可以在业务代码中拿到当前代理对象,可以解决比如在同一个service层调用事务方法,事务失效的问题。

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);

// Get the interception chain for this method.

//查找spring容器中,所有的拦截器对象

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.

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...

MethodInvocation invocation =

new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);

// Proceed to the joinpoint through the interceptor chain.

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);

}

}

}

//调用器调用逻辑


@Override

@Nullable

public Object proceed() throws Throwable {
   
   

// We start with an index of -1 and increment early.

//是否是最后一个拦截器了,如果是调用目标方法

if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
   
   

return invokeJoinpoint();

}

//获取下一个要执行的拦截器

Object interceptorOrInterceptionAdvice =

this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);

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.

//调用拦截器

return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);

}

}

//拦截器调用图解 通过递归调用,调用所有的拦截器,直到调用到最后一个拦截器时候,调用目标方法。

image.png

相关文章
|
2月前
|
Java
Spring5入门到实战------9、AOP基本概念、底层原理、JDK动态代理实现
这篇文章是Spring5框架的实战教程,深入讲解了AOP的基本概念、如何利用动态代理实现AOP,特别是通过JDK动态代理机制在不修改源代码的情况下为业务逻辑添加新功能,降低代码耦合度,并通过具体代码示例演示了JDK动态代理的实现过程。
Spring5入门到实战------9、AOP基本概念、底层原理、JDK动态代理实现
|
7天前
|
设计模式 Java 测试技术
spring复习04,静态代理动态代理,AOP
这篇文章讲解了Java代理模式的相关知识,包括静态代理和动态代理(JDK动态代理和CGLIB),以及AOP(面向切面编程)的概念和在Spring框架中的应用。文章还提供了详细的示例代码,演示了如何使用Spring AOP进行方法增强和代理对象的创建。
spring复习04,静态代理动态代理,AOP
|
9天前
|
XML 缓存 Java
spring源码剖析-spring-beans(内部核心组件,BeanDefinition的注册,BeanWapper创建)
spring源码剖析-spring-beans(内部核心组件,BeanDefinition的注册,BeanWapper创建)
38 10
|
9天前
|
XML 存储 Java
spring源码刨析-spring-beans(内部核心组件,beanDefinition加载过程)
spring源码刨析-spring-beans(内部核心组件,beanDefinition加载过程)
|
20天前
|
Java 数据库连接 数据库
Spring基础3——AOP,事务管理
AOP简介、入门案例、工作流程、切入点表达式、环绕通知、通知获取参数或返回值或异常、事务管理
Spring基础3——AOP,事务管理
|
2月前
|
人工智能 自然语言处理 Java
Spring AI,Spring团队开发的新组件,Java工程师快来一起体验吧
文章介绍了Spring AI,这是Spring团队开发的新组件,旨在为Java开发者提供易于集成的人工智能API,包括机器学习、自然语言处理和图像识别等功能,并通过实际代码示例展示了如何快速集成和使用这些AI技术。
Spring AI,Spring团队开发的新组件,Java工程师快来一起体验吧
|
2月前
|
XML Java 数据格式
Spring5入门到实战------11、使用XML方式实现AOP切面编程。具体代码+讲解
这篇文章是Spring5框架的AOP切面编程教程,通过XML配置方式,详细讲解了如何创建被增强类和增强类,如何在Spring配置文件中定义切入点和切面,以及如何将增强逻辑应用到具体方法上。文章通过具体的代码示例和测试结果,展示了使用XML配置实现AOP的过程,并强调了虽然注解开发更为便捷,但掌握XML配置也是非常重要的。
Spring5入门到实战------11、使用XML方式实现AOP切面编程。具体代码+讲解
|
2月前
|
缓存 Java 开发者
Spring高手之路22——AOP切面类的封装与解析
本篇文章深入解析了Spring AOP的工作机制,包括Advisor和TargetSource的构建与作用。通过详尽的源码分析和实际案例,帮助开发者全面理解AOP的核心技术,提升在实际项目中的应用能力。
23 0
Spring高手之路22——AOP切面类的封装与解析
|
2月前
|
安全 Java 开发者
Java 新手入门:Spring 两大利器IoC 和 AOP,小白也能轻松理解!
Java 新手入门:Spring 两大利器IoC 和 AOP,小白也能轻松理解!
31 1
|
2月前
|
Java API Spring
Spring Boot 中的 AOP 处理
对 Spring Boot 中的切面 AOP 做了详细的讲解,主要介绍了 Spring Boot 中 AOP 的引入,常用注解的使用,参数的使用,以及常用 api 的介绍。AOP 在实际项目中很有用,对切面方法执行前后都可以根据具体的业务,做相应的预处理或者增强处理,同时也可以用作异常捕获处理,可以根据具体业务场景,合理去使用 AOP。
下一篇
无影云桌面