Spring AOP使用注解版

该博客介绍了如何在Spring中配置和使用AOP(面向切面编程)来实现方法运行日志的记录。通过创建切面类,定义切入点表达式,以及使用Before、After、AfterReturning和AfterThrowing注解,博主详细展示了如何在方法调用前后插入日志打印,包括方法参数、执行结果和异常处理情况。示例代码中包含了配置类、业务逻辑类和切面类的实现。

/**
 * 1.导入AOP的依赖: spring-aspects包
 * 2.定义一个页面逻辑类
 * 3.定义一个切面类
 * 4.将切面类和业务逻辑类加入到spring容器
 * 5.为了区分哪个类是切面类,给切面类加@Aspect注解
 * 6.开启注解版的事务@EnableAspectJAutoProxy
 *
 */

@EnableAspectJAutoProxy
@Configuration
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){
         return i/j;
    }
}






//切面类



@Aspect
public class LogAspects {



    //抽取公共的接入点表达式
    @Pointcut("execution(public int com.mytest.AOP.MathCalculator.*(..))")
    public void pointCut(){

    }
    //内部的点入店直接用方法名,
    @Before("pointCut()")
    public void logStart(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        System.out.println(joinPoint.getSignature().getName()+"运行。。。参数列表是:{}"+ Arrays.asList(args));
    }
    @After("com.mytest.AOP.LogAspects.pointCut()")
    public void logEnd(JoinPoint joinPoint) {
        System.out.println(joinPoint.getSignature().getName()+"除法结束。。。");
    }
    //returning="result“,result对应方法的参数result,JoinPoint必须出现在方法参数列表的最前面
    @AfterReturning(value = "pointCut()",returning = "result")
    public void logReturn(JoinPoint joinPoint,Object result) {
        System.out.println("除法正常返回。。。运行结果{}"+result);
    }
    @AfterThrowing(value = "pointCut()",throwing = "e")
    public void logException(JoinPoint joinPoint,Exception e) {
        System.out.println("除法异常、、、异常信息:{}"+e);
    }
}





//测试类
public class TestAop {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(MainConfigOfAOP.class);
       MathCalculator math= context.getBean(MathCalculator.class);
        System.out.println(math.div(10, 3));

    }
}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值