浅谈Spring自定义注解从入门到精通
作者:Java知音_ 时间:2023-11-25 03:59:12
在业务开发过程中我们会遇到形形色色的注解,但是框架自有的注解并不是总能满足复杂的业务需求,我们可以自定义注解来满足我们的需求。根据注解使用的位置,文章将分成字段注解、方法、类注解来介绍自定义注解
字段注解
字段注解一般是用于校验字段是否满足要求,hibernate-validate依赖就提供了很多校验注解 ,如@NotNull、@Range等,但是这些注解并不是能够满足所有业务场景的。比如我们希望传入的参数在指定的String集合中,那么已有的注解就不能满足需求了,需要自己实现。
自定义注解
定义一个@Check注解,通过@interface声明一个注解
@Target({ ElementType.FIELD})
//只允许用在类的字段上
@Retention(RetentionPolicy.RUNTIME)
//注解保留在程序运行期间,此时可以通过反射获得定义在某个类上的所有注解
@Constraint(validatedBy = ParamConstraintValidated.class)
public @interface Check {
/**
* 合法的参数值
**/
String[] paramValues();
/**
* 提示信息
**/
String message() default "参数不为指定值";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
@Target 定义注解的使用位置,用来说明该注解可以被声明在那些元素之前。
ElementType.TYPE:说明该注解只能被声明在一个类前。
ElementType.FIELD:说明该注解只能被声明在一个类的字段前。
ElementType.METHOD:说明该注解只能被声明在一个类的方法前。
ElementType.PARAMETER:说明该注解只能被声明在一个方法参数前。
ElementType.CONSTRUCTOR:说明该注解只能声明在一个类的构造方法前。
ElementType.LOCAL_VARIABLE:说明该注解只能声明在一个局部变量前。
ElementType.ANNOTATION_TYPE:说明该注解只能声明在一个注解类型前。
ElementType.PACKAGE:说明该注解只能声明在一个包名前
@Constraint 通过使用validatedBy来指定与注解关联的验证器
@Retention用来说明该注解类的生命周期。
RetentionPolicy.SOURCE: 注解只保留在源文件中
RetentionPolicy.CLASS : 注解保留在class文件中,在加载到JVM虚拟机时丢弃
RetentionPolicy.RUNTIME: 注解保留在程序运行期间,此时可以通过反射获得定义在某个类上的所有注解。
验证器类
验证器类需要实现ConstraintValidator泛型接口
public class ParamConstraintValidated implements ConstraintValidator<Check, Object> {
/**
* 合法的参数值,从注解中获取
* */
private List<String> paramValues;
@Override
public void initialize(Check constraintAnnotation) {
//初始化时获取注解上的值
paramValues = Arrays.asList(constraintAnnotation.paramValues());
}
public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
if (paramValues.contains(o)) {
return true;
}
//不在指定的参数列表中
return false;
}
}
第一个泛型参数类型Check:注解,第二个泛型参数Object:校验字段类型。需要实现initialize和isValid方法,isValid方法为校验逻辑,initialize方法初始化工作
使用方式
定义一个实体类
@Data
public class User {
/**
* 姓名
* */
private String name;
/**
* 性别 man or women
* */
@Check(paramValues = {"man", "woman"})
private String sex;
}
对sex字段加校验,其值必须为woman或者man
测试
@RestController("/api/test")
public class TestController {
@PostMapping
public Object test(@Validated @RequestBody User user) {
return "hello world";
}
}
注意需要在User对象上加上@Validated注解,这里也可以使用@Valid注解
方法、类注解
在开发过程中遇到过这样的需求,如只有有权限的用户的才能访问这个类中的方法或某个具体的方法、查找数据的时候先不从数据库查找,先从guava cache中查找,在从redis查找,最后查找mysql(多级缓存)。
这时候我们可以自定义注解去完成这个要求,第一个场景就是定义一个权限校验的注解,第二个场景就是定义spring-data-redis包下类似@Cacheable的注解。
权限注解
自定义注解
@Target({ ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PermissionCheck {
/**
* 资源key
* */
String resourceKey();
}
该注解的作用范围为类或者方法上
* 类
public class PermissionCheckInterceptor extends HandlerInterceptorAdapter {
/**
* 处理器处理之前调用
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod)handler;
PermissionCheck permission = findPermissionCheck(handlerMethod);
//如果没有添加权限注解则直接跳过允许访问
if (permission == null) {
return true;
}
//获取注解中的值
String resourceKey = permission.resourceKey();
//TODO 权限校验一般需要获取用户信息,通过查询数据库进行权限校验
//TODO 这里只进行简单演示,如果resourceKey为testKey则校验通过,否则不通过
if ("testKey".equals(resourceKey)) {
return true;
}
return false;
}
/**
* 根据handlerMethod返回注解信息
*
* @param handlerMethod 方法对象
* @return PermissionCheck注解
*/
private PermissionCheck findPermissionCheck(HandlerMethod handlerMethod) {
//在方法上寻找注解
PermissionCheck permission = handlerMethod.getMethodAnnotation(PermissionCheck.class);
if (permission == null) {
//在类上寻找注解
permission = handlerMethod.getBeanType().getAnnotation(PermissionCheck.class);
}
return permission;
}
}
权限校验的逻辑就是你有权限你就可以访问,没有就不允许访问,本质其实就是一个 * 。我们首先需要拿到注解,然后获取注解上的字段进行校验,校验通过返回true,否则返回false
测试
@GetMapping("/api/test")
@PermissionCheck(resourceKey = "test")
public Object testPermissionCheck() {
return "hello world";
}
该方法需要进行权限校验所以添加了PermissionCheck注解
缓存注解
自定义注解
@Target({ ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomCache {
/**
* 缓存的key值
* */
String key();
}
注解可以用在方法或类上,但是缓存注解一般是使用在方法上的
切面
@Aspect
@Component
public class CustomCacheAspect {
/**
* 在方法执行之前对注解进行处理
*
* @param pjd
* @param customCache 注解
* @return 返回中的值
* */
@Around("@annotation(com.cqupt.annotation.CustomCache) && @annotation(customCache)")
public Object dealProcess(ProceedingJoinPoint pjd, CustomCache customCache) {
Object result = null;
if (customCache.key() == null) {
//TODO throw error
}
//TODO 业务场景会比这个复杂的多,会涉及参数的解析如key可能是#{id}这些,数据查询
//TODO 这里做简单演示,如果key为testKey则返回hello world
if ("testKey".equals(customCache.key())) {
return "hello word";
}
//执行目标方法
try {
result = pjd.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return result;
}
}
因为缓存注解需要在方法执行之前有返回值,所以没有通过 * 处理这个注解,而是通过使用切面在执行方法之前对注解进行处理。如果注解没有返回值,将会返回方法中的值
测试
@GetMapping("/api/cache")
@CustomCache(key = "test")
public Object testCustomCache() {
return "don't hit cache";
}
小结
本篇文章主要介绍了开发过程中遇到自定义注解的场景以及自定义注解实现。如有纰漏,欢迎指正。
源码
https://github.com/TiantianUpup/custom-annotation
来源:https://blog.csdn.net/weixin_38405253/article/details/100151657
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android自定义View原理(实战)
![](https://img.aspxhome.com/file/2023/1/139271_0s.png)
Java实现的3des加密解密工具类示例
浅谈android nexus私服的使用
![](https://img.aspxhome.com/file/2023/0/139050_0s.png)
android截屏功能实现代码
![](https://img.aspxhome.com/file/2023/3/87533_0s.jpg)
C#中的静态成员、静态方法、静态类介绍
![](https://img.aspxhome.com/file/2023/1/92961_0s.jpg)
详解Java异常处理中finally子句的运用
JDBC环境设置(中文详解)
详解Spring框架入门
![](https://img.aspxhome.com/file/2023/3/69943_0s.png)
Java硬币翻转倍数递增试算实例
JAVA多线程之实现用户任务排队并预估排队时长
![](https://img.aspxhome.com/file/2023/1/80941_0s.gif)
Java Cookie与Session实现会话跟踪详解
![](https://img.aspxhome.com/file/2023/8/78378_0s.png)
java 在Jetty9中使用HttpSessionListener和Filter
java实现简单的加减乘除计算器
![](https://img.aspxhome.com/file/2023/9/72599_0s.jpg)
Android仿美团外卖菜单界面
Android 刘海屏适配总结(推荐)
![](https://img.aspxhome.com/file/2023/9/90139_0s.jpg)
Android中去掉标题栏的几种方法(三种)
![](https://img.aspxhome.com/file/2023/5/102575_0s.png)
分享两种实现Winform程序的多语言支持的多种解决方案
SpringBoot 2.x 整合Lombok的方法示例
![](https://img.aspxhome.com/file/2023/2/88222_0s.jpg)
C#套接字(Socket)通信之UDP组播详解
Android使用Kotlin实现多节点进度条
![](https://img.aspxhome.com/file/2023/7/87327_0s.jpg)