Spring AOP(0)演示代码

//配置类
@Configuration
@EnableAspectJAutoProxy
public class MainConfigOfAOP {
    @Bean
    public MathCalculator mathCalculator(){
        return new MathCalculator();
    }
    @Bean
    public LogAspects logAspects(){
        return new LogAspects();
    }
}
//业务逻辑组件
public class MathCalculator {
//目标方法
    public int div(int i ,int j){
        System.out.println("MathCalculator....div....");
        return i/j;
    }
}

//日志切面组件,在目标方法div()的执行前后等打印相关日志。
@Aspect
public class LogAspects {
    @Pointcut("execution(public * com.atguigu.aop.MathCalculator.*(..))")
    public void pointCut(){}

    @Before("pointCut()")
    public void logStart(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        System.out.println(""+joinPoint.getSignature().getName()+"运行。。。@Before参数列表是:{"+ Arrays.asList(args)+"}");

    }
    //JoinPoint作为方法的参数,一定要放在参数的第一位,否则会报错
    @After("pointCut()")
    public void logEnd(JoinPoint joinPoint){
        System.out.println(""+joinPoint.getSignature().getName()+"除法结束@After...");
    }
    @AfterReturning(value = "pointCut()",returning = "result")
    public void logReturn(JoinPoint joinPoint,Object result){
        System.out.println(""+joinPoint.getSignature().getName()+"正常返回。。。。@AfterReturning运行结果:{"+result+"}");
    }
    @AfterThrowing(value = "pointCut()",throwing = "exception")
    public void logSException(JoinPoint joinPoint,Exception exception){
        System.out.println(""+joinPoint.getSignature().getName()+"异常。。。@AfterThrowing异常信息:{"+exception +"}");
    }
    //环绕通知,动态代理,手动推进目标方法运行(joinPoint。procced)
//    public void log(){
//        System.out.println("除法运行。。。参数列表是:{}");
//    }
}
//测试类
public class IOCTest_AOP {
    @Test
    public void test01(){
        AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext(MainConfigOfAOP.class);
//注意:这里不可以使用注释里面的方式调用目标方法,因为只有由spring容器创建的bean,才能使spring的
//功能。
        //MathCalculator mathCalculator=new MathCalculator ();
        //mathCalculator.div(1,1);
        MathCalculator mathCalculator = ac.getBean(MathCalculator.class);
        mathCalculator.div(1,1);
        ac.close();
    }
}

spring版本:(version:5.2.5);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值