自定义注解使用SPEL表达式绑定动态变量参数值

半世苍凉 提交于 2020-08-06 03:41:01

1、定义注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OperationLog {
	String module();
	String operation();
	String businessId() default "";
}

2、定义AOP

@Service
@Aspect
public class OperationLogAop {
	@After("@annotation(operationLog)")
	public void interceptOperation(JoinPoint point, OperationLog operationLog) {
		String module = operationLog.module();
		String operation = operationLog.operation();
		String businessIdSpel = operationLog.businessId();
		Object[] args = point.getArgs();
		Method method = ((MethodSignature) point.getSignature()).getMethod();
		//获取被拦截方法参数名列表(使用Spring支持类库)
		LocalVariableTableParameterNameDiscoverer localVariableTable = new LocalVariableTableParameterNameDiscoverer();
		String[] paraNameArr = localVariableTable.getParameterNames(method);
		//使用SPEL进行key的解析
		ExpressionParser parser = new SpelExpressionParser();
		//SPEL上下文
		StandardEvaluationContext context = new StandardEvaluationContext();
		//把方法参数放入SPEL上下文中
		for(int i=0;i<paraNameArr.length;i++) {
			context.setVariable(paraNameArr[i], args[i]);
		}
		String businessId = null;
		// 使用变量方式传入业务动态数据
		if(businessIdSpel.matches("^#.*.$")) {
			businessId = parser.parseExpression(businessIdSpel).getValue(context, String.class);
		}
		System.out.println(businessId);
	}
}

3、使用注解

@OperationLog(module = "role", operation = "insert", businessId = "#entity.name")
@PostMapping("/insert")
public void insert(Role entity) {

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!