spring boot AOP的两种常见用法
第一种、元注解方式,一般用于事先取值或封装已知字典,日志等操作
Annotation类userAnnotation
注解含义自行百度
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface userAnnotation {
String value() default "";
}
model类
public class User {
private String name;
private String address;
service类
@Service
public class UserService {
public String users(User user){
System.out.println(JSON.toJSONString(user));
return JSON.toJSONString(user);
}
}
切面类
可以通过Pointcut表达,然后Around引用或者直接引用对应的元注解包即可
@Aspect
@Component
public class userAspect {
@Resource
UserService userService;
/**
* 切面元注解形式
*/
// @Pointcut("@annotation(cn.zgc.annotation.userAnnotation)")
// public void userPointCut() {}
// @Around("userPointCut()")
@Around("@annotation(cn.zgc.annotation.userAnnotation)()")
public void around(ProceedingJoinPoint point) throws Throwable {
MethodSignature methodSignature = (MethodSignature) point.getSignature();
Method method = methodSignature.getMethod();
userAnnotation userAnnotation = method.getAnnotation(userAnnotation.class);
String value = userAnnotation.value();
User user = new User();
user.setName(value);
try {
userService.users(user);
} catch (Exception e) {
}
}
controller类
@RestController
@RequestMapping
@Validated
public class userController {
//通过切面,会获取到当前参数,进行切面处理或各自的业务封装
@userAnnotation(value = "张三")
@GetMapping("/list1")
public Object list(){
return "user";
}
第二种、execution表达式方法
用处更广,通过表达式切面到某个文件下所有方法
@Pointcut("execution(* cn.zgc.controller.userController.*(..))")
public void userAspect(){
}
@Around("userAspect()")
public void userAspect1(JoinPoint joinPoint){
Object[] args = joinPoint.getArgs();//获取入参,进行业务逻辑操作
System.out.println("userAspect切面");
}