• spring aop的使用


    1、aop的概念就不说了,看看常用aop增强处理方式

    before            ->    前置之增强处理,在目标方法执行之前织入增强处理;
    AfterReturning    ->    后置增强处理,在目标方法正常执行(不出现异常)后织入增强处理;
    AfterThrowing     ->    异常增强处理,在目标方法抛出异常后织入增强处理;
    after             ->    最终增强处理,不管方法是否抛出异常,都会在目标方式执行之后执行;
    Around            ->    环绕增强处理,在目标方法前后都可以织入增强处理。

    2、aop进行xml配置比较麻烦,这里我们使用注解配置

    这里顺便说一下,proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。首先说明下proxy-target-class="true"和proxy-target-class="false"的区别,为true则是基于类的代理,默认是false,基于接口创建;

    如果类中的注入是@autowired(基于接口的)  用这种:

    <!-- 启动对于@AspectJ -->

    <aop:aspectj-autoproxy/>

    如果类中的注入是@Resouce用下面这种:

    <!-- 启动对于@AspectJ -->

    <aop:aspectj-autoproxy proxy-target-class="true"/>

     

    3、类中设置

    package com.utils;
    
    //定义 一个切面
    @Aspect 
    //定义一个bean组件   
    @Component
    public class MyLogger {
        private static final Logger logger = Logger.getLogger(MyLogger.class);
        /**
         * 注意: around通知织入的是ProceedingJoinPoint ,而其他的通知织入的是JoinPoint
         * execution(* com.service.*.*(..))
         * 任意修饰符   com.service包下的任意类下的任意方法任意参数,都将被捕获 
         */
        @Around("execution(* com.service.*.*(..))")
        public void show(ProceedingJoinPoint join) {
              //获取类的名称
            String className = join.getTarget().getClass().getSimpleName();
            //获取方法名称
            String methodName = join.getSignature().getName();
            //获取参数信息
            String args = Arrays.toString(join.getArgs());
            logger.info(className+"中的"+methodName+"参数是["+args+"]的方法执行了!");       
        }
        
        /**
         * 也可以使用切点签名的方式
         * 如下面这种形式
         */
        @Pointcut("execution(* com.service.*.*(..))")
        public void cut() {}
        
        @Before("cut()")
        public void before(JoinPoint join) {
            
            //获取类的名称
            String className = join.getTarget().getClass().getSimpleName();
            //获取方法名称
            String method = join.getSignature().getName();
            //获取参数信息
            String args = Arrays.toString(join.getArgs());
            
            System.out.println(className+"的"+method+"执行了");
        }
    }
  • 相关阅读:
    如何避免重复的开发
    用BPM解决企业信息化的数据孤岛
    撸代码之前我们应该想些什么
    从开发的角度去分解项目需求
    MQTT 无法连接问题排查
    Linux下的OpenSSH,你知道多少?
    Linux下Rsyslog日志远程集中式管理
    如何在Linux下部署Samba服务?
    Linux环境下安装配置vsftpd服务(三种认证模式)
    Linux集群环境下NTP服务器时间同步
  • 原文地址:https://www.cnblogs.com/newbest/p/9739713.html
Copyright © 2020-2023  润新知