谈到前置增强和后置增强,就必须理解切入点(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.结果展示