给初学者分享一下利用反射加AOP做的自定义注解,用来数据校验挺不错的,自己用着玩的
1.自定义注解
* 注解验证
*
* @author syliu
* @create 2017/10/31 0031
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
@Documented
public @interface ValidAnnotations {
String[] target() default {};
}
2.自定义拦截器
package com.syliu.waiting.common.domain;
import com.syliu.waiting.common.exception.GlobalException;
import lombok.val;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.lang.reflect.Method;
import java.util.Map;
/**
*
* @author syliu
*/
@Aspect
@Component
public class ValidSecureAspect {
public final static Logger log = LoggerFactory.getLogger(ValidSecureAspect.class);
@Before("@annotation(nonEmpty)")
public void validSecure(JoinPoint point, ValidAnnotations nonEmpty){
//获取注解的参数
String[] target = nonEmpty.target();
//如果注解参数不为空
if (!StringUtils.isEmpty(target)){
//获取入参
Object[] args = point.getArgs();
if (!StringUtils.isEmpty(args)){
val arg = args[0];
checkField(arg,target);
}else {
throw new GlobalException("参数为空",-1);
}
}
}
public void checkField(Object object,String[] target){
if(StringUtils.isEmpty(object)){
throw new GlobalException("参数为空",-1);
}
//获取类型名称
final String typeName = object.getClass().getTypeName();
if (Map.class.getTypeName().equals(typeName)){
Map map=(Map)object;
//循环取值,从map中获取value
for (String targets : target) {
Object o = map.get(target);
if (StringUtils.isEmpty(o)){
throw new GlobalException(targets+":is Empty",-1);
}
}
}else if (Object.class.getTypeName().equals(typeName)){
for (String name: target) {
final Object fieldValue = getFieldValue(object, name);
if (StringUtils.isEmpty(fieldValue)){
throw new GlobalException(name+":is Empty",-1);
}
}
}else if (typeName.startsWith("com.syliu")){
for (String name: target) {
final Object fieldValue = getFieldValue(object, name);
if (StringUtils.isEmpty(fieldValue)){
throw new GlobalException(name+":is Empty",-1);
}
}
}
}
public Object getFieldValue(Object object,String name){
Object value=null;
if(!StringUtils.isEmpty(name)){
String upperName = name.substring(0, 1).toUpperCase()
+ name.substring(1);
try {
Method method=object.getClass()
.getMethod("get" + upperName);
value = method.invoke(object);
} catch (Exception e) {
}
}
return value;
}
}
3.用法
@ValidAnnotations(target ={"password","username"})
@Override
public Result reg(UserEntity userEntity) {
String username = userEntity.getUsername();
UserEntity user=userRepository.findByUsername(username);
if (StringUtils.isEmpty(user)){
UserEntity save = userRepository.save(userEntity);
return new Result(getUserInfo(save));
}
throw new GlobalException(ResultEnum.USER_HASED);
}