SpringBoot下的代理注解

@EnableAspectJAutoProxy

java 复制代码
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {
	
    // 是否代理目标对象,ture:使用CGLIB代理 fasle:使用JDK代理
	boolean proxyTargetClass() default false;
	
    // 是否暴露代理对象
	boolean exposeProxy() default false;

}

@EnableAspectJAutoProxy 是一个Spring框架的注解,用于启用基于AspectJ的代理支持。它允许您使用面向切面编程 (AOP) 来实现横切关注点,例如日志记录、性能监控、事务管理等。

具体来说,@EnableAspectJAutoProxy 做了以下几件事情:

1、启用代理机制:它启用了Spring容器的代理功能,允许Spring创建代理对象,以拦截和处理方法调用,正常来说是不需要主动去加该注解,因为由于SpringBoot的自动配置会将代理机制自动开启,具体实现可参考本文最后推荐博文。

2、使用AspectJ注解:它启用了AspectJ注解,使您可以在Spring中使用 @Aspect@Before@After@Around 等注解来定义切面。

3、配置代理模式:它允许您选择代理的模式,通常是 proxyTargetClassexposeProxy 选项。proxyTargetClass 默认为 false,表示使用标准的JDK动态代理,如果将其设置为 true,则使用CGLIB代理。exposeProxy 默认为 false,表示不将当前代理对象暴露给切面,如果将其设置为 true,可以通过 AopContext.currentProxy() 获取当前代理对象。

以下是一个示例:

java 复制代码
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
public class AppConfig {
    // Other bean configurations can go here
}

典型应用

1、解决由于代理实现的机制的失效问题:

比如@Transactional事务、@Async异步,Service内部方法自调用导致的失效

java 复制代码
// 配置暴露代理类,通过获取代理类调取方法
((TUserService) AopContext.currentProxy()).updateRealNameById(id, realName);

参考文章:【精选】Spring源码深度解析:十四、@Aspect方式的AOP上篇 - @EnableAspectJAutoProxy_enableaspectjautoproxy 是哪个包_代码的知行者的博客-CSDN博客

相关推荐
咖啡Beans25 分钟前
使用OpenFeign实现微服务间通信
java·spring cloud
我不是混子28 分钟前
说说单例模式
java
间彧3 小时前
SimpleDateFormat既然不推荐使用,为什么java 8+中不删除此类
java
金銀銅鐵3 小时前
Spring 中的 initializeBean 方法的内部逻辑小总结
spring
间彧3 小时前
DateTimeFormatter相比SimpleDateFormat在性能上有何差异?
java
间彧3 小时前
为什么说SimpleDateFormat是经典的线程不安全类
java
MacroZheng3 小时前
横空出世!MyBatis-Plus 同款 ES ORM 框架,用起来够优雅!
java·后端·elasticsearch
用户0332126663674 小时前
Java 查找并替换 Excel 中的数据:详细教程
java
间彧4 小时前
ThreadLocal实现原理与应用实践
java