• spring框架AOP前置增强和后置增强


    谈到前置增强和后置增强,就必须理解切入点(pointcut),我刚开始也不是太理解它是怎么实现前置增强和后置增强的,其中主要原因是忽略了切入点,下面请看示例:

    只展示部分代码!

    1.前置增强代码

    package com.aop;
    
    import java.lang.reflect.Method;
    import java.util.Arrays;
    
    import org.apache.log4j.Logger;
    import org.springframework.aop.MethodBeforeAdvice;
    /**
     * 
     * @author Mr
     * 前置增强
     */
    public class LoggerBefore implements MethodBeforeAdvice {
        //创建类的log对象
        private static final Logger log = Logger.getLogger(LoggerBefore.class);
        
        @Override
        public void before(Method method, Object[] arguments, Object target)
                throws Throwable {
            
            log.info("调用了"+target+"的"+method.getName()+"方法。方法参数是"+Arrays.toString(arguments));
    
        }
    
    }

    2.后置增强代码

    package com.aop;
    
    import java.lang.reflect.Method;
    
    import org.apache.log4j.Logger;
    import org.springframework.aop.AfterReturningAdvice;
    /**
     * 
     * @author Mr
     * 后置增强
     */
    public class LoggerAfterReturing implements AfterReturningAdvice {
        //创建类的log对象
        private static final Logger log = Logger.getLogger(LoggerAfterReturing.class);
        
        @Override
        public void afterReturning(Object returnValue, Method method, Object[] arguments,
                Object target) throws Throwable {
            
            log.info("调用了"+target+"的"+method.getName()+"方法。方法返回值是"+returnValue);
    
        }
    
    }

    3.applicationContext.xml配置文件内容,其中实体类和dao以及biz等的实现类就不展示了

    <bean id="dao" class="com.dao.impl.IUserDaoImpl"></bean>
        <bean id="biz" class="com.biz.impl.IUserBizImpl">
            <!-- 要引用dao -->
            <property name="dao" ref="dao"></property>
        </bean>
        
        <bean id="logbefore" class="com.aop.LoggerBefore"></bean>
        <bean id="logafter" class="com.aop.LoggerAfterReturing"></bean>
        
        
        <aop:config>
            <!-- 引用的是biz中的 -->
            <aop:pointcut expression="execution(public void save(com.domain.User))" id="pointcut"/>    
            <!-- 将增强处理和切入点结合在一起,在切入点处插入增强处理,完成“织入” -->
            <aop:advisor advice-ref="logbefore" pointcut-ref="pointcut"/>
            <aop:advisor advice-ref="logafter" pointcut-ref="pointcut"/>
        </aop:config>

    4.结果展示

  • 相关阅读:
    Codeforces Round #518 (Div. 1) Computer Game 倍增+矩阵快速幂
    BZOJ2756 [SCOI2012]奇怪的游戏 最大流
    Codeforces Global Round 1 (CF1110) (未完结,只有 A-F)
    [AtCoder] NIKKEI Programming Contest 2019 (暂缺F)
    [AtCoder] Yahoo Programming Contest 2019
    Codeforces Round #538 (Div. 2) (CF1114)
    [BZOJ3625][Codeforces Round #250]小朋友和二叉树 多项式开根+求逆
    [BZOJ2341][Shoi2011]双倍回文 manacher+std::set
    [BZOJ4278] [ONTAK2015]Tasowanie 贪心+后缀数组
    [BZOJ3451] Tyvj1953 Normal 点分治+FFT
  • 原文地址:https://www.cnblogs.com/myhzb/p/7530552.html
Copyright © 2020-2023  润新知