基于spring boot 自定义注解实现aop对方法的增强
文章中的例子内容是json schema的校验所以根据自己的业务需求去完善。如果直接复制可能会找不到json解析方法。
导入依赖
需要导入aop相关依赖springboot提供aop的start
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
注解标识
标识的使用是配合pointCut找到对应的方法
package com.example.webtest.config.aop;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Description json解析验证标识
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface JSONParser {
}
切面实现
@PointCut猪解中(execution)的语法
public * com.example.webtest.controller..(..)
修饰符 返回值 包路径及方法名(返回值) *号表示任意匹配,返回值..表示任意参数
package com.example.webtest.config.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* @Description 验证json格式切面
*/
@Aspect
@Component
public class JSONParserInterceptor {
@Pointcut("execution(public * com.example.webtest.controller.*.*(..)) && @annotation(com.example.webtest.config.aop.JSONParser)")
public void pointCut() {
}
@Around("pointCut()")
public Object jsonParser(ProceedingJoinPoint joinPoint) throws Throwable {
//验证json格式
Object[] args = joinPoint.getArgs();
String content = String.valueOf(args[1]);
//json schema约束验证
Boolean validate = JSONValidate.jsonSchemaValidate(content.replaceAll("'", "\""));
Object proceed = joinPoint.proceed();
System.out.println("通知结束");
return proceed;
}
}
测试
package com.example.webtest.controller;
import com.example.webtest.config.aop.JSONValidate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class WebTestController {
@RequestMapping("/getTest")
@JSONParser
public String getTest(@RequestBody String strObj) {
System.out.println("测试参数: " + strObj);
return strObj;
}
}