SpringBoot 自定义注解及 AOP 的开发和使用

1,717 阅读2分钟

在公司项目中,如果需要做一些公共的功能,如日志等,最好的方式是使用自定义注解,自定义注解可以实现我们对想要添加日志的方法上添加,这篇文章基于日志功能来讲讲自定义注解应该如何开发和使用。

一、引入 AOP 依赖

自定义注解一般会和AOP(切面)结合使用,所以我们首先需要在项目中引入相应的依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

二、创建自定义注解Log

annotation.Log:

import java.lang.annotation.*;  
  
@Target(ElementType.METHOD)  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
public @interface Log {  
    String value() default "";  
}
  • @Target: 表明该注解可以作用的目标是谁,也就是你的注解是用来修饰方法?类?还是属性?这里是表明作用在方法上。
  • @Retention: 表明该注解作用的生命周期,这里表明在运行时有效。
  • @Documented: 表明被它修饰的注解将被javadoc提取成文档。

三、创建AOP切面类

aspect.LogAspect:

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Modifier;

@Aspect
@Component
public class LogAspect {
    @Pointcut("@annotation(com.jk.annotation.Log)")
    public void pointCut() {
    }

    @Before("pointCut()")
    public void before() {
        System.out.println("前置通知...");
    }

    @After("pointCut()")
    public void after() {
        System.out.println("后置通知...");
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕通知前...");
        Object result = joinPoint.proceed();
        System.out.println("环绕通知后...");

        print(joinPoint);

        return result;
    }

    private static void print(ProceedingJoinPoint joinPoint) {
        System.out.println("目标方法名为:" + joinPoint.getSignature().getName());
        System.out.println("目标方法所属类的简单类名:" + joinPoint.getSignature().getDeclaringType().getSimpleName());
        System.out.println("目标方法所属类的类名:" + joinPoint.getSignature().getDeclaringTypeName());
        System.out.println("目标方法声明类型:" + Modifier.toString(joinPoint.getSignature().getModifiers()));
        //获取传入目标方法的参数
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            System.out.println("第" + (i + 1) + "个参数为:" + args[i]);
        }
        System.out.println("被代理的对象:" + joinPoint.getTarget());
        System.out.println("代理对象自己:" + joinPoint.getThis());
    }
}
  • @Aspect: 表明该类为切面类,定义切面类时必须加这个注解。
  • @Component: 表明把该类交给IOC容器控制。
  • @Pointcut: 定义切入点,结合@annotation(@interface)使用,表明该方法为切入点。@interface必须写自定义注解的全路径名。
  • @Before: 表明被自定义注解代理的方法执行前,先调用的方法。
  • @After: 表明被自定义注解代理的方法执行后,return前调用的方法。
  • @Around: 将被自定义注解代理的方法封装起来,环绕通知(即在他之前之后通知),point.proceed()表明执行的目标方法。
  • print方法: 通过切点反射获取方法名、类名、参数等。

四、自定义注解测试

controller.TestController:

import com.jk.annotation.Log;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RestController;  
  
@RestController  
@RequestMapping("/test")  
public class TestController {  
    @GetMapping  
    @Log  
    public void test() {  
        System.out.println("执行test方法");
    }  
}

test()方法上添加了一个@Log注解,他会在执行这个方法时,执行我们之前定义切面时创建的前置方法、后置方法、环绕方法。

image.png

SpringBoot中使用自定义注解就是如此简单,一般在通知方法中我们还会结合反射来获取执行方法的一些信息,如方法名,参数,响应值等,在后面我也会新开一篇文章专门讲讲反射,有兴趣的掘友可以关注一下哦!