springboot基于注解aop
我们现在创建一个去掉参数空格的aop
1.创建Annotation
/**
* 加上该注解,可以去掉方法参数对象中String类型字段的前后空格
* 如果exclude设置为true,则不会去掉该字段的前后空格
*/
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TrimBlankAnnotation {
boolean exclude() default false;
}
2.创建Aspect
@Aspect
@Component
@Configuration
@Slf4j
public class TrimBlankAspect {
@Pointcut("@annotation(com.paic.property.cfom.common.annotation.TrimBlankAnnotation)")
public void pointcut() {
}
@Before(value = "pointcut()")
public void before(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
if(args != null && args.length > 0){
for (Object obj : args) {
process(obj);
}
}
}
private void process(Object obj) {
if (obj == null) {
return;
}
Class clazz = obj.getClass();
if (clazz.isArray()) {
Object[] arrayObj = (Object[]) obj;
if (arrayObj != null && arrayObj.length > 0) {
trimBlank(arrayObj);
}
} else if (obj instanceof Collection) {
Collection objects = (Collection) obj;
if (objects != null && objects.size() > 0) {
trimBlank(objects.toArray());
}
} else if (clazz.isAnnotationPresent(TrimBlankAnnotation.class)) {
trimBlank(obj);
}
}
private void trimBlank(Object[] objects) {
for (Object obj : objects) {
process(obj);
}
}
private void trimBlank(Object obj) {
Class clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
try {
for (Field field : fields) {
Class fieldType = field.getType();
if (fieldType == String.class) {
TrimBlankAnnotation fieldAnnotation = field.getAnnotation(TrimBlankAnnotation.class);
if (fieldAnnotation == null || !fieldAnnotation.exclude()) {
field.setAccessible(true);
Object fieldValue = field.get(obj);
if (fieldValue != null) {
field.set(obj, fieldValue.toString().trim());
}
field.setAccessible(false);
}
} else {
field.setAccessible(true);
Object fieldValue = field.get(obj);
field.setAccessible(false);
process(fieldValue);
}
}
} catch (Exception ex) {
log.error("TrimBlankAspect异常[{}]", obj, ex);
}
}
}
3.应用aop注解