springboot实现aop

1.定义动作类
@Component
public class ProductService {
    public void doSomeService(){
        System.out.println("doSomeService");
    }
}

2.定义切面类
@Aspect
@Component
public class LoggerAspect {
	//@Pointcut(value = "execution(* com.example.demo.aop.ProductService.*(..))")
	//public void annotationPointCut(){};
    @Around(value = "execution(* com.example.demo.aop.ProductService.*(..))")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("start log:" + joinPoint.getSignature().getName());
        Object object = joinPoint.proceed();
        System.out.println("end log:" + joinPoint.getSignature().getName());
        return object;
    }
}

@Around表明这是一个切面,可以使用@pointCut的方式定义切点,当然也可以直接将切点定义在具体的建言(@Around)——也就是具体的切点执行内容中。
更多的建言还有@Before、@After、@AfterThrowing、@AfterReturning。

3.配置类
@ComponentScan("com.example.demo.aop")
@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
}

使用@EnableAspectJAutoProxy注解开启Spring对AspectJ的支持,这个是必须的。网络上很多人说并不一定需要这个,springboot默认已经开启,但我多次尝试后,确定没有它切面压根不会执行

4.测试
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DiConfig.class);
        ProductService productService = context.getBean(ProductService.class);
        productService.doSomeService();
        context.close();
    }
}

完成以上动作后,就可以编码测试了,如图,前后都执行了切点方法。
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值