Spring——AOP(通知)

1. 搭建项目环境

2. 新建lib文件夹,添加spring依赖jar包:
spring-beans.jar、spring-context.jar、spring-core.jar、spring-expression.jar、【spring-aop.jar】

添加依赖包: commons-logging.jar、【aopalliance.jar】

3. 在项目src目录下新建applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

</beans>

4. 编辑dao、service等源码

5.在 applicationContext.xml的<beans>节点中管理bean对象实例
<!-- 实际对象 -->
<bean id="userDao" class="aop.UserDaoImpl"></bean>

6.定义通知类
//前置通知--MethodBeforeAdvice
public class LogBeforeAdvice implements MethodBeforeAdvice {
public void before(Method method, Object[] args, Object target) throws Throwable {}
}
//后置通知 --AfterReturningAdvice
public class LogAfterAdvice implements AfterReturningAdvice {
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {}
}
//环绕通知--MethodInterceptor
public class LogAroundAdvice implements MethodInterceptor {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
//调用方法
Object returnValue = methodInvocation.proceed();
}
}
//异常通知--ThrowsAdvice
public class LogThrowsAdvice implements ThrowsAdvice {
public void afterThrowing(Method m, Object[] args, Object target, Throwable throwable) {}
}
7.在 applicationContext.xml的<beans>节点中管理通知对象实例
<!-- 前置通知 -->
<bean id="logBeforeAdvice" class="aop.advice.LogBeforeAdvice"></bean>
<!-- 后置通知 -->
<bean id="logAfterAdvice" class="aop.advice.LogAfterAdvice"></bean>
<!-- 环绕通知 -->
<bean id="logAroundAdvice" class="aop.advice.LogAroundAdvice"></bean>
<!-- 异常通知 -->
<bean id="logThrowsAdvice" class="aop.advice.LogThrowsAdvice"></bean>

8.在 applicationContext.xml的<beans>节点中配置代理工厂实例
<!-- 代理工厂 bean -->
<bean id="proxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 代理的接口 -->
<property name="proxyInterfaces" value="aop.IUserDao"/>
<!-- 代理的目标对象 -->
<property name="target" ref="userDao"/>
<!-- 通知列表 -->
<property name="interceptorNames">
<list>
<!--<value>logBeforeAdvice</value>前置通知-->
<!-- <value>logAfterAdvice</value> --><!--后置通知-->
<!-- <value>logAroundAdvice</value> --><!-- 环绕通知 -->
<value>logThrowsAdvice</value>
</list>
</property>
</bean>

9.测试
//加载xml文档
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");

//无代理,无通知
IUserDao dao = (IUserDao)factory.getBean("userDao");
//dao.updateUser();

//有代理,有通知
IUserDao proxyUserDao = (IUserDao)factory.getBean("proxyFactoryBean");
proxyUserDao.updateUser();

posted @ 2016-12-03 14:14  龙之天族  阅读(210)  评论(0编辑  收藏  举报