1.獲取方法參數(shù)
// 定義切點(diǎn)
@Pointcut("@annotation(com.example.springbootredisson.annotation.Lock)")
public void pointCut(){
}
@Around("pointCut()")
public Object pointCut(ProceedingJoinPoint joinPoint){
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//獲取注解參數(shù)值
Lock lock = methodSignature.getMethod().getAnnotation(Lock.class);
String prefix = lock.prefix();
String spELString = lock.suffix();
// 通過joinPoint獲取被注解方法
String value = generateKeyBySpEL(spELString, joinPoint);
// 解析后的參數(shù)可以繼續(xù)做后續(xù)增加業(yè)務(wù)處理 例:加鎖
// 執(zhí)行業(yè)務(wù)邏輯
return joinPoint.proceed();
}
2.解析SPEL中的表達(dá)式
if(StringUtils.isBlank(spELString)){
return null;
}
// 通過joinPoint獲取被注解方法
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
//創(chuàng)建解析器
SpelExpressionParser parser = new SpelExpressionParser();
//獲取表達(dá)式
Expression expression = parser.parseExpression(spELString);
//設(shè)置解析上下文(有哪些占位符,以及每種占位符的值)
EvaluationContext context = new StandardEvaluationContext();
//獲取參數(shù)值
Object[] args = joinPoint.getArgs();
//獲取運(yùn)行時(shí)參數(shù)的名稱
DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
String[] parameterNames = discoverer.getParameterNames(method);
for (int i = 0; i < parameterNames.length; i++) {
context.setVariable(parameterNames[i],args[i]);
}
//解析,獲取替換后的結(jié)果
String result = expression.getValue(context).toString();
System.out.println(result);
return result;
3.使用方法
/**
* get請(qǐng)求承耿,解析請(qǐng)求頭中的參數(shù)
* @param orderId
*/
@GetMapping("test")
@Lock(prefix = "test",suffix = "#orderId")
public void test(@RequestParam(value = "orderId") Integer orderId){
System.out.println(orderId);
}
/**
* post請(qǐng)求拳球,解析請(qǐng)求體中的參數(shù)
* @param id
*/
@Lock(prefix = "test",suffix = "#user.id")
@PostMapping("goods")
public void goods(@RequestBody User user){
System.out.println(user);
}