Spring——AOP(通知)

本文详细介绍如何使用Spring框架实现面向切面编程(AOP),包括搭建项目环境、配置Spring XML文件、定义通知类及创建代理工厂等步骤,并通过示例演示如何在实际应用中引入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();

转载于:https://www.cnblogs.com/ccw95/p/6128665.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值