阅读本文大概须要 5 分钟。javascript
做者:何甜甜在吗
连接:https://juejin.im/post/5cf376e16fb9a07eee5eb6ebphp
字段注解
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 {};
}
java
ElementType.TYPE
:说明该注解只能被声明在一个类前。
ElementType.FIELD
:说明该注解只能被声明在一个类的字段前。
ElementType.METHOD
:说明该注解只能被声明在一个类的方法前。
ElementType.PARAMETER
:说明该注解只能被声明在一个方法参数前。
ElementType.CONSTRUCTOR
:说明该注解只能声明在一个类的构造方法前。
ElementType.LOCAL_VARIABLE
:说明该注解只能声明在一个局部变量前。
ElementType.ANNOTATION_TYPE
:说明该注解只能声明在一个注解类型前。
ElementType.PACKAGE
:说明该注解只能声明在一个包名前
RetentionPolicy.SOURCE
: 注解只保留在源文件中
RetentionPolicy.CLASS
: 注解保留在class文件中,在加载到JVM虚拟机时丢弃
RetentionPolicy.RUNTIME
: 注解保留在程序运行期间,此时能够经过反射得到定义在某个类上的全部注解。
验证器类
ConstraintValidator
泛型接口
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";
}
}
web
User
对象上加上
@Validated
注解,这里也能够使用
@Valid
注解,
@Validated 和 @Valid 的区别,这篇建议看下。
方法、类注解
guava cache
中查找,在从
redis
查找,最后查找
mysql
(多级缓存)。
spring-data-redis
包下相似
@Cacheable
的注解。
权限注解
自定义注解
@Target({ ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PermissionCheck {
/**
* 资源key
* */
String resourceKey();
}
redis
拦截器类
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;
}
}
spring
true
,不然返回
false
测试
@GetMapping("/api/test")
@PermissionCheck(resourceKey = "test")
public Object testPermissionCheck() {
return "hello world";
}
sql
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";
}
推荐阅读:
微信扫描二维码,关注个人公众号
朕已阅
本文分享自微信公众号 - 程序员的成长之路(cxydczzl)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。