Spring--基于注解的aop实现

1首先编写业务类,如:

@Configuration
public class MathCalculator {
    public int div(int i,int j){
        System.out.println("目标方法正在执行》》》》》》》》》》》》》");
        return i/j;
    }

2.编写aop类,写入前置,后置,返回,异常通知的方法,在对应的方法上分别加上相应的注解:

注意,此处会将AOP的相关类和业务类进行关联,可以用@PointCut切入,也可以直接在各个方法上的注解上直接切入

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;

import java.util.Arrays;

/**
 * @Aspect告诉spring此类是一个切面类
 */
@Aspect
public class LogAspect {


    //抽取公共切入点
    //其他的切面类引用
    //其他切面类引用
    @Pointcut("execution(public int com.example.spring03.aop.MathCalculator.*(..))")
    public void pointCut(){

    }

    @Before("pointCut()")
    public void logStart(JoinPoint joinpoint){
        System.out.println(joinpoint.getSignature().getName()+"开始运行了,参数列表:"+ Arrays.asList(joinpoint.getArgs()));
    }

    @After(value = "pointCut()")
    public void logEnd(JoinPoint joinPoint){
        System.out.println(joinPoint.getSignature().getName()+"运行结束了!");
    }

    @AfterReturning(value = "pointCut()",returning = "result")
    public void logReturn(JoinPoint joinPoint,Object result){
        System.out.println(joinPoint.getSignature().getName()+"运行结束,返回结果:"+result.toString());
    }

    @AfterThrowing(value = "pointCut()",throwing = "exception")
    public void logException(JoinPoint joinPoint,Exception exception){
        System.out.println(joinPoint.getSignature().getName()+"运行出现异常,异常信息:"+exception.toString());
    }

}

3.将aop相关的类和业务类都加入到IOC容器中,并开启基于注解的AOP模式

import com.example.spring03.aop.LogAspect;
import com.example.spring03.aop.MathCalculator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
 * @EnableAspectJAutoProxy开启基于注解的AOP模式
 */

@EnableAspectJAutoProxy
@Configuration
public class ConfigOfAop {

    @Bean
    public MathCalculator mathCalculator(){
        return new MathCalculator();
    }

    @Bean
    public LogAspect logAspect(){
        return new LogAspect();
    }


}

4.编写测试类,此时获取容器中的业务类的实例,必须通过IOC容器获取,IOC容器会自动调用相应的AOP方法

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值