问题
业务流程处理中,很多的方法都需要对传入的参数对象做公共的处理(比如:字符串去空格)。
思路
看到公共处理,就联系到《Spring-AOP》,对方法进行拦截处理。但问题是如果有很多方法需要进行相同的公共处理,而每个方法都需要编写一个切面类,会使得代码重复率增加。
然后我们联想到使用注解的方式,每个需要增强的方法前加上一个注解,然后对注解进行拦截,进而就可以对标注该注解的方法进行拦截处理了。
Spring使用自定义annotation+aop 来实现预处理。
步骤
- 自定义一个annotation用于标记需要处理的地方。
- 创建切面类。在pointcut时对annotation进行拦截,在@Around环绕通知里面获取@annotation对应的当前对象,获取当前对象参数,并修改参数内容,然后proceed一下,继续执行。
实际代码
项目结构
实体类
Product:
package com.ymqx.pojo;
import org.springframework.stereotype.Component;
@Component
public class Product {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
服务类
ProductService:
package com.ymqx.service;
import com.ymqx.annotation.AnnoLog;
import com.ymqx.pojo.Product;
import org.springframework.stereotype.Service;
@Service("productService")
public class ProductService {
@AnnoLog("lalalalala")
public Product doSomeService(Product pd){
System.out.println("doSomeService");
return pd;
}
}
对服务类ProductService的doSomeService方法进行自定义注解标注@AnnoLog(“lalalalala”)
自定义的注解类
AnnoLog:
package com.ymqx.annotation;
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AnnoLog {
String value() default "";
}
自定义注解AnnoLog,ElementType.METHOD表示该注解仅能作用于方法上。
自定义注解类的切面类
AnnoLogAspect:
package com.ymqx.aspect;
import com.ymqx.annotation.AnnoLog;
import com.ymqx.pojo.Product;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.lang.reflect.Modifier;
@Aspect
@Component
public class AnnoLogAspect {
@Pointcut("@annotation(com.ymqx.annotation.AnnoLog)")
private void pointcut1() {}
@Around("pointcut1() && @annotation(logger)")
public Object advice(ProceedingJoinPoint joinPoint, AnnoLog logger) {
/* 1、获取注解作用的类信息 */
System.out.println("1、注解作用的方法名: " + joinPoint.getSignature().getName());
System.out.println("1、所在类的简单类名: " + joinPoint.getSignature().getDeclaringType().getSimpleName());
System.out.println("1、所在类的完整类名: " + joinPoint.getSignature().getDeclaringType());
System.out.println("1、目标方法的声明类型: " + Modifier.toString(joinPoint.getSignature().getModifiers()));
/* 2、获取注解内容 */
System.out.println("2、AnnoLog日志的内容为[" + logger.value() + "]");
/* 3、获取注解作用方法参数、返回值 */
Object[] args = joinPoint.getArgs();
System.out.println("3、请求参数args=["+args+"]");
Object result = null;
try {
result = joinPoint.proceed(args);
System.out.println("3、响应结果result=["+result+"]");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
/* 4、获取注解作用方法参数、返回值 */
if(result instanceof Product) {
Product product = (Product) result;
System.out.println("4、id="+product.getId());
product.setId(product.getId() + 2);
return product;
}
return result;
}
}
@Aspect 表明AnnoLogAspect是个切面类。
@Component 表示这是一个bean,由Spring进行管理。
@Pointcut("@annotation(com.ymqx.annotation.AnnoLog)") private void pointcut1() {};声明了切点,切点是我们自定义的注解类。
@Around(“pointcut1() && @annotation(logger)”):@Around声明了通知内容,在具体的通知中,我们通过@annotation(logger拿到了自定义的注解对象,所以就能够获取我们在使用注解时赋予的值了。
通过调用proceed()方法,执行了实际的操作,并获取到了返回值,然后对返回值进行个性化操作(加减、去空格等)。
配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<context:component-scan base-package="com.ymqx"/>
<aop:aspectj-autoproxy/>
</beans>
测试类
TestSpring:
package com.ymqx.test;
import com.ymqx.pojo.Product;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ymqx.service.ProductService;
public class TestSpring {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "applicationContext.xml" });
ProductService productService = (ProductService) context.getBean("productService");
Product product = new Product();
product.setId(1);
System.out.println("调用前TestSpring:id="+product.getId());
productService.doSomeService(product);
System.out.println("调用后TestSpring:id="+product.getId());
}
}
结果输出:
调用前TestSpring:id=1
1、注解作用的方法名: doSomeService
1、所在类的简单类名: ProductService
1、所在类的完整类名: class com.ymqx.service.ProductService
1、目标方法的声明类型: public
2、AnnoLog日志的内容为[lalalalala]
3、请求参数args=[[Ljava.lang.Object;@682b2fa]
ProductService:doSomeService
3、响应结果result=[com.ymqx.pojo.Product@217ed35e]
4、id=1
调用后TestSpring:id=3
结果看样看到,调用方法doSomeService后,对象product的id增加了2。
@Around通知处,只要有@annotion()就可以了,其实不需要pointcut()。
AnnoLogAspect:
@Aspect
@Component
public class AnnoLogAspect {
@Around("@annotation(logger)")
public Object advice(ProceedingJoinPoint joinPoint, AnnoLog logger) {
...
}
}
直接使用@Around("@annotation(logger)")即可。
说了这么多,其实还没解决问题(去空格)。有了上面的基础,其实只需要在切面类编写逻辑即可。
/* 4、获取注解作用方法参数、返回值 */
System.out.println("4、响应result=["+result.getClass()+"]");
Field[] fields = result.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
System.out.println("4、field=[" + field.get(result) + "]");
if(field.get(result) instanceof String) {
field.set(result, field.get(result).toString().trim());
}
}
完整代码:
去空格注解
Trimmed:
package com.ymqx.annotation;
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Trimmed {
public static enum TrimmerType {
SIMPLE, ALL_WHITESPACES, EXCEPT_LINE_BREAK;
}
TrimmerType value() default TrimmerType.ALL_WHITESPACES;
}
定义枚举变量。SIMPLE:去前后空格;ALL_WHITESPACES去除所有空格;EXCEPT_LINE_BREAK:除换行符以外的空格。
去空格注解切面
TrimmedAspect:
package com.ymqx.aspect;
import com.ymqx.annotation.Trimmed;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Aspect
@Component
public class TrimmedAspect {
@Around("@annotation(trimmed)")
public Object advice(ProceedingJoinPoint joinPoint, Trimmed trimmed) throws IllegalAccessException, InstantiationException {
/* 1、获取注解作用的类信息 */
System.out.println("1、注解作用的方法名: " + joinPoint.getSignature().getName());
System.out.println("1、所在类的简单类名: " + joinPoint.getSignature().getDeclaringType().getSimpleName());
System.out.println("1、所在类的完整类名: " + joinPoint.getSignature().getDeclaringType());
System.out.println("1、目标方法的声明类型: " + Modifier.toString(joinPoint.getSignature().getModifiers()));
/* 2、获取注解内容 */
System.out.println("2、AnnoLog日志的内容为[" + trimmed.value() + "]");
/* 3、获取注解作用方法参数、返回值 */
Object[] args = joinPoint.getArgs();
System.out.println("3、请求参数args=["+args+"]");
Object result = null;
try {
result = joinPoint.proceed(args);
System.out.println("3、响应结果result=["+result+"]");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
/* 4、获取注解作用方法参数、返回值 */
System.out.println("4、响应result=["+result.getClass()+"]");
Field[] fields = result.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
System.out.println("4、field=[" + field.get(result) + "]");
if(field.get(result) instanceof String) {
Pattern p = null;
Matcher m = null;
String str = null;
switch (trimmed.value()){
case SIMPLE:
field.set(result, field.get(result).toString().trim());
break;
case ALL_WHITESPACES:
p = Pattern.compile("\\s*|\t|\r|\n");
m = p.matcher(field.get(result).toString());
str = m.replaceAll("");
field.set(result, str);
break;
case EXCEPT_LINE_BREAK:
p = Pattern.compile("\\s*|\t|\r");
m = p.matcher(field.get(result).toString());
str = m.replaceAll("");
field.set(result, str);
break;
default:
System.out.println("4、error trimmed.value()");
break;
}
}
}
return result;
}
}
服务类
ProductService:
package com.ymqx.service;
import com.ymqx.annotation.Trimmed;
import com.ymqx.pojo.Product;
import org.springframework.stereotype.Service;
@Service("productService")
public class ProductService {
@Trimmed(Trimmed.TrimmerType.SIMPLE)
public Product doSomeService(Product pd){
System.out.println("doSomeService");
return pd;
}
}
添加@Trimmed注解。
调用
TestSpring:
public class TestSpring {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "applicationContext.xml" });
ProductService productService = (ProductService) context.getBean("productService");
Product product = new Product();
product.setId(1);
product.setName(" LI LI ");
System.out.println("调用前TestSpring:name="+product.getName());
productService.doSomeService(product);
System.out.println("调用后TestSpring:name="+product.getName());
}
}
运行结果
调用前TestSpring:name= LI LI
1、注解作用的方法名: doSomeService
1、所在类的简单类名: ProductService
1、所在类的完整类名: class com.ymqx.service.ProductService
1、目标方法的声明类型: public
2、AnnoLog日志的内容为[SIMPLE]
3、请求参数args=[[Ljava.lang.Object;@6743e411]
doSomeService
3、响应结果result=[com.ymqx.pojo.Product@3eb25e1a]
4、响应result=[class com.ymqx.pojo.Product]
4、field=[1]
4、field=[ LI LI ]
调用后TestSpring:name=LI LI
如果服务类注解修改为 @Trimmed(Trimmed.TrimmerType.ALL_WHITESPACES),结果如下:
调用前TestSpring:name= LI LI
1、注解作用的方法名: doSomeService
1、所在类的简单类名: ProductService
1、所在类的完整类名: class com.ymqx.service.ProductService
1、目标方法的声明类型: public
2、AnnoLog日志的内容为[ALL_WHITESPACES]
3、请求参数args=[[Ljava.lang.Object;@6743e411]
doSomeService
3、响应结果result=[com.ymqx.pojo.Product@3eb25e1a]
4、响应result=[class com.ymqx.pojo.Product]
4、field=[1]
4、field=[ LI LI ]
调用后TestSpring:name=LILI
product对象的name空格全部去除。故可以通过在方法上添加注解值动态执行相应逻辑。