目錄結構:

一:自定義注解
package org.example.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; //表示該注解只可以在方法上使用。 @Target(ElementType.METHOD)
//表示該注解一直存活到被加載進JVM。
@Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { String message() default ""; int code() default 0; }
@Target:
//作用於類、接口和枚舉上 ElementType.TYPE //作用於字段、枚舉常量 ElementType.FIELD //作用於方法上 ElementType.METHOD //作用於方法的參數上 ElementType.PARAMETER //作用於構造函數上 ElementType.CONSTRUCTOR //作用於局部變量上 ElementType.LOCAL_VARIABLE //作用於注解上 ElementType.ANNOTATION_TYPE //作用於包上 ElementType.PACKAGE
@Retention:
用於聲明注解的生命周期。 //注解僅僅保存於源碼中,在被編譯成class文件時就失效 RetentionPolicy.SOURCE //默認策略,在編譯成class文件后仍有效,在被裝載進JVM時就失效 RetentionPolicy.CLASS //在JVM中仍存在,可以通過反射獲取到注解的屬性值 RetentionPolicy.RUNTIME
@Inherited:表示該注解可以被繼承。
@Document:表示該注解會被加載進Javadoc中。
二:DemoController
@RestController @RequestMapping("demo") public class DemoController { @GetMapping @MyAnnotation(message = "songkw", code = 23) public Object demo() { return "annotation test"; } }
三:AOP
@Aspect @Component public class DemoAOP { @Before(value = "execution(public * org.example.controller.*.*(..))")
//@Before(value = "@annotation(org.example.annotation.MyAnnotation)") public void before(JoinPoint joinPoint) throws NoSuchMethodException { Object target = joinPoint.getTarget(); MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = target.getClass().getMethod(signature.getName(), signature.getParameterTypes()); MyAnnotation annotation = method.getAnnotation(MyAnnotation.class); int code = annotation.code(); String message = annotation.message(); System.err.println("code:" + code); System.err.println("message:" + message); } }
四:啟動類
@SpringBootApplication(scanBasePackages = {"org.example.*"})
@EnableAspectJAutoProxy
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}
五:pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
