1.添加所需要的依赖
org.springframework.boot spring-boot-starter-aop
2.包名目录如图所示
3.AddLog.java文件 (注解文件)
package com.aivoicetech.annotion;
import java.lang.annotation.*;
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface AddLog {//Annotation 类型定义为@interface, 所有的Annotation 会自动继承java.lang.Annotation这一接口,并且不能再去继承别的类或是接口。 AddLog为注解名称
String[] value() default {};
}
4.AddLogAop.java (自定义注解要实现的功能)
package com.aivoicetech.annotion;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Aspect
@Component
public class AddLogAop {
private static final Log log = LogFactory.getLog(AddLogAop.class);
@Pointcut("@annotation(com.aivoicetech.annotion.AddLog)")
private void getAddLogPointCut() {
}
@Before("@annotation(addLog)")
public void doAddLog(JoinPoint joinPoint,AddLog addLog) {
String[] value = addLog.value();
log.info("使用了注解,value值为:"+Arrays.toString(value));
}
@After("@annotation(addLog)")
public void afterExecute(JoinPoint joinPoint,AddLog addLog) {
log.info("方法执行完成...");
}
}
5.TestController.java (测试注解)
package com.aivoicetech.controller;
import com.aivoicetech.annotion.AddLog;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/test")
@AddLog(value = "123")
public String test(){
System.out.println("方法执行中。。。");
return "test";
}
}
访问该接口,控制台打印如下
由此可见,注解使用成功
通过本案例进行改造,可以完成注解的其它功能,例如:添加日志、参数校验等等



