在公司项目中,如果需要做一些公共的功能,如日志等,最好的方式是使用自定义注解,自定义注解可以实现我们对想要添加日志的方法上添加,这篇文章基于日志功能来讲讲自定义注解应该如何开发和使用。
一、引入 AOP 依赖
自定义注解一般会和AOP(切面)结合使用,所以我们首先需要在项目中引入相应的依赖。
            
            
              xml
              
              
            
          
          <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
        二、创建自定义注解Log
annotation.Log:
            
            
              java
              
              
            
          
          import java.lang.annotation.*;  
  
@Target(ElementType.METHOD)  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
public @interface Log {  
    String value() default "";  
}
        @Target:表明该注解可以作用的目标是谁,也就是你的注解是用来修饰方法?类?还是属性?这里是表明作用在方法上。@Retention:表明该注解作用的生命周期,这里表明在运行时有效。@Documented:表明被它修饰的注解将被javadoc提取成文档。
三、创建AOP切面类
aspect.LogAspect:
            
            
              java
              
              
            
          
          import org.aspectj.lang.ProceedingJoinPoint;  
import org.aspectj.lang.annotation.*;  
import org.springframework.stereotype.Component;  
  
@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 void around(ProceedingJoinPoint point) throws Throwable {  
        System.out.println("环绕通知前...");  
        point.proceed();  
        System.out.println("环绕通知后...");  
    }  
}
        @Aspect:表明该类为切面类,定义切面类时必须加这个注解。@Component:表明把该类交给IOC容器控制。@Pointcut:定义切入点,结合@annotation(@interface)使用,表明该方法为切入点。@interface必须写自定义注解的全路径名。@Before:表明被自定义注解代理的方法执行前,先调用的方法。@After:表明被自定义注解代理的方法执行后,return前调用的方法。@Around:将被自定义注解代理的方法封装起来,环绕通知(即在他之前之后通知),point.proceed()表明执行的目标方法。
四、自定义注解测试
controller.TestController:
            
            
              java
              
              
            
          
          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注解,他会在执行这个方法时,执行我们之前定义切面时创建的前置方法、后置方法、环绕方法。

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