1.AOP简单上手
AOP(Aspect Oriented Programming),意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。它通过对既有程序定义一个切入点,然后在其前后切入不同的执行内容,比如常见的有:打开数据库连接/关闭数据库连接、打开事务/关闭事务、记录日志等。AOP可以降低耦合,把通用的业务提出来,提高代码的可重用性,同时提高开发的效率,使开发人员只关心真正的业务逻辑.
- 引入AOP的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
@EnableAspectJAutoProxy已经默认开启,不需要在启动类上添加.
而当我们需要使用CGLIB来实现AOP的时候,需要配置spring.aop.proxy-target-class=true.但是注意:高版本spring自动根据运行类选择JDK或CGLIB代理,也就是当运行类没有继承接口,spring也会自动使用CGLIB代理。我们无需设置proxy-target-class属性,JDK动态代理是模拟接口实现的方式,cglib是模拟子类继承的方式,一般采用前者,因为前者效率高。
2 简单示例
@Aspect
@Component
public class LogAspect {
@Around(value = "execution(* com.jun.test.microservice..*(..))")
public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint){
Object returnVal = null;
final Logger log = getLog(proceedingJoinPoint);
final String methodName = proceedingJoinPoint.getSignature().getName();
try {
final Object[] args = proceedingJoinPoint.getArgs();
final String arguments;
if (args == null || args.length == 0) {
arguments = "";
} else {
arguments = Arrays.deepToString(args);
}
log.info