使用AOP获取自定义注解的内容

目录结构:

一:自定义注解

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
View Code

@Retention:

用于声明注解的生命周期。
//注解仅仅保存于源码中,在被编译成class文件时就失效
RetentionPolicy.SOURCE
//默认策略,在编译成class文件后仍有效,在被装载进JVM时就失效
RetentionPolicy.CLASS
//在JVM中仍存在,可以通过反射获取到注解的属性值
RetentionPolicy.RUNTIME
View Code

@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>

猜你喜欢

转载自www.cnblogs.com/monument/p/12932545.html
今日推荐