spring boot AOP的两种常见用法

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切面");	
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值