自定义注解
在 Spring Boot 中,可以创建自定义注解来简化代码和提高可读性。自定义注解可以帮助我们在应用程序中更好地表达代码的意图和功能。
1.首先,需要创建一个注解类。注解类是一个带有 @interface 注解的接口。例如,以下是一个简单的自定义注解类:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthRole {
String value();
}
@Target表是注解的作用对象
类型 | 作用范围 | 示例 |
---|---|---|
METHOD | 可以用于方法上 | @Controller |
FIELD | 可以用于字段上 | @NotNull |
PARAMETER | 可以用于方法参数上 | @Transactional |
xxxxxxxxxx @Componentpublic class UserService { // 相关方法和属性省略}@Componentpublic class UserController { @Autowired private UserService userService; // 相关方法省略}java | 可以用于其他注解类型 | @Controller |
在创建自定义注解时,需要使用 @Retention(RetentionPolicy.RUNTIME) 注解来指定该注解的生命周期。
类型 | 作用 |
---|---|
SOURCE | 注解只在源代码中存在,在编译后就会被丢弃。 |
CLASS | 注解在编译后会被保留在字节码中,在运行时无法访问到 |
RUNTIME | 注解在运行时可以被访问到,可以通过反射机制获取到注解中的属性值 |
ANNOTATION_TYPE | 注解只能用于注解类型上,而不能用于方法或字段上 |
2.然后,创建一个切面类,用于拦截带有自定义注解的方法:
@Component
@Aspect
public class AopConfig {
//声明切面
@Pointcut("@annotation(com.example.elkdemo.annotation.AuthRole)")
public void pointcut() {
}
@Before("pointcut()")
public void before(JoinPoint joinPoint) {
//获取注解中的内容
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
AuthRole annotation = signature.getMethod().getAnnotation(AuthRole.class);
String value = annotation.value();
System.out.println(value);
}
}
3.使用注解
@RestController
@RequestMapping("test")
public class TestController {
@AuthRole(value = "test")
@GetMapping("aop")
public void testAop() {
System.out.println("测试题aop");
}
}