注解方式实现AOP

导入相关依赖
		 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>
业务代码部分
@RestController
public class TestController {
    
    @GetMapping("/hi")
    public String sayHi(String name){
        System.out.println("hi " + name);
        return name;
    }
}
声明切面类
@Component
//将该类声明为日志切面
@Aspect
public class LogAspect {

    //声明方法为前置通知
    @Before("execution(* com.aop.TestController.sayHi(..))")
    //@Before("execution( * com.aop.TestController.*(..))")  表示对TestController类下的所有方法起作用
    public void beforeMethod(JoinPoint joinPoint) {

        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        //获取参数
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println("the method "+methodName+" begin with"+args);
    }

    //后置通知(无论方法是否出现异常均要执行)
    //无法在后置通知中获取返回值
    @After("execution(* com.aop.TestController.sayHi(..))")
    public void afterMethod() {
        System.out.println("method end");
    }

    //返回通知
    //正常执行完毕后可获取到返回值
    @AfterReturning(value = "execution(* com.aop.TestController.sayHi(..))",returning = "ret")
    public void afterReturningMethod(Object ret) {
        System.out.println("ret = " +ret);
    }

   /*
    补充:
    切面优先级:
        当多个切面类同时作用于一个方法时,可以使用注解 @Order(1)修饰切面类,指定其优先级,值越小优先级越高。
        @Component
        @Aspect
        @Order(1)
        public class LogAspect {..}


    切入点表达式的重用:
        声明一个方法:
            @Pointcut("execution(* com.aop.TestController.sayHi(..))")
            public void pointcuts(){//什么都不用写}
        使用方法:
            @Before("pointcuts()")
            public void beforeMethod(JoinPoint joinPoint) {..}
   */

}
测试

浏览器访问:http://127.0.0.1:8080/hi?name=kohen

打印结果:

the method sayHi begin with[kohen]
hi kohen
method end
ret = kohen
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值