美文网首页spring 相关
Spring 注解--AOP基本用法

Spring 注解--AOP基本用法

作者: aix91 | 来源:发表于2019-01-03 13:34 被阅读0次

    1.面向切面编程器AOP

    在程序运行期间,动态的将代码切入到指定位置运行。

    2. 基本语法

    1. 通知方法
    • 前置通知(@Before)
    • 后置通知(@After)
    • 返回通知 (@AfterReturning)
    • 异常通知 (@AfterThrowing)
    • 环绕通知 (@Around)
    1. @PointCut:公共切入点表达式
    2. JoinPoint: 作为函数的参数传入切面方法,可以得到目标方法的相关信息
    3. @Aspect : 指定切面类
    4. @EnableAspectJAutoProxy : 开启基于注解的AOP模式

    3. 实例

    1. 定义目标类
    public class MathCalculator {
        public int div(int x, int y) {
            System.out.println(x / y);
            return x / y;
        }
    }
    
    1. 定义切面类,并指定通知方法
    @Aspect
    public class LogAspects {
        @Pointcut("execution(int com.test.tornesol.util.spring.spring_aop.MathCalculator.div(int,int))")
        public void pointCut() { }
    
        @Before("com.test.tornesol.util.spring.spring_aop.LogAspects.pointCut()")
        public void logStart(JoinPoint joinPoint) {
            System.out.println(joinPoint.getSignature().getName() + " 除法运行,参数是:" + Arrays.asList(joinPoint.getArgs()));
        }
    
        @After("com.test.tornesol.util.spring.spring_aop.LogAspects.pointCut()")
        public void logEnd() {
            System.out.println("除法结束");
        }
    
    
        @AfterReturning(value = "com.test.tornesol.util.spring.spring_aop.LogAspects.pointCut())", returning = "result")
        public void logReturn2(JoinPoint joinPoint, Object result) {
            System.out.println(joinPoint.getSignature().getName() + "除法返回" + result);
        }
    
        @AfterThrowing(value = "com.test.tornesol.util.spring.spring_aop.LogAspects.pointCut()", throwing = "exception")
        public void logException(Exception exception) {
            System.out.println("除法异常");
        }
    }
    

    Notes: 注意给切面类添加@Aspect注解

    1. 添加Configuration类,注入目标类和切面类,并开启AOP代理模式
    @Configuration
    @EnableAspectJAutoProxy//开启基于注解的AOP模式
    public class MainConfig {
        @Bean
        public MathCalculator mathCalculator() {
            return new MathCalculator();
        }
        @Bean
        public LogAspects logAspects() {
            return new LogAspects();
        }
    }
    

    4.测试 输出

    public class AopDemo {
        static public void main(String[] args) {
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
            context.getBean(MathCalculator.class).div(4, 2);
        }
    }
    
    div 除法运行,参数是:[4, 2]
    2
    除法结束
    div除法返回2
    

    相关文章

      网友评论

        本文标题:Spring 注解--AOP基本用法

        本文链接:https://www.haomeiwen.com/subject/chnxrqtx.html