springAOP实现

AOP定义
AOP就是 Aspect Oriented Programming的缩写,意思为面向切面编程。通过预编译的方式以及动态代理的方式实现程序同一维护的功能。AOP是Spring中的重要内容,利用AOP可以增强主业务的功能,降低主业务和基础重复性的业务耦合度,提高程序的可重用性,提高开发效率。
原理

AOP中的关键名词概念:
1.Aspect 切面 其实就是代理对象
2.Advice 通知 主业务之外添加的功能
通知又分为多种:
前置通知:在切点方法调用之前执行
后置通知:在切点方法调用之后执行
异常通知:再切点方法发生异常时执行
环绕通知:包含了前置通知,后置通知,异常通知的通知
3.point 切点 表示要对切面中那个方法进行增强
4.WeAVing 织入 将通知添加到切点中的操作,也就是生成动态代理的过程。

public class MyAdvice {
public void before() {
System.out.println("[前置通知]===》安全检查");
}

public void after1(Object returnValue) {
System.out.println("[后置通知]===》记录用户的行为,存入人民币是: " + returnValue+"万");
}
public void after2() {
System.out.println("[后置通知]===》清除缓存 ");
}
public void throwing(Exception e) {
System.out.println("[异常通知], 发生的异常是: " + e.getClass().getName());
}
}

xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--创建dao对象-->
<bean id="payDao" class="com.bjsxt.dao.impl.PayDaoImpl" />
<!--创建service对象-->
<bean id="paymentService" class="com.bjsxt.service.impl.PaymentImpl">
<!--DI注入,调用set方法-->
<property name="payDao" ref="payDao" />
</bean>
<!--创建通知对象-->
<bean id="myAdvice" class="com.bjsxt.advice.MyAdvice"/>
<!--配置aop-->
<aop:config>
<!--配置切点-->通知要织入到哪些类的哪些方法中
<aop:pointcut id="pc" expression="execution(* com.bjsxt.service.*.*(..))" />
<!--配置切面-->要给哪个对象生成代理对象
<aop:aspect ref="myAdvice">
<!--前置通知,业务方法执行之前执行-->
<aop:before method="before" pointcut-ref="pc" />
<!--后置通知,业务方法执行之后执行-->
<aop:after-returning method="after1" returning="returnValue" pointcut-ref="pc"/>
<!--后置通知,业务方法执行之后执行-->
<!--多个后置通知,执行的顺序按照此处的配置顺序执行-->
<aop:after-returning method="after2" pointcut-ref="pc"/>
<!--异常通知,业务方法发生异常后执行-->
<aop:after-throwing method="throwing" throwing="e" pointcut-ref="pc" />
</aop:aspect>
</aop:config>
</beans>

猜你喜欢

转载自www.cnblogs.com/sxshe/p/12165805.html