AOP中关键性概念
- 1. AOP
- 2. AOP带来的好处
- 3 工具类org.springframework.aop.framework.ProxyFactoryBean用来创建一个代理对象,在一般情况下它需要注入以下三个属性:
- 4. 前置通知(org.springframework.aop.MethodBeforeAdvice):在连接点之前执行的通知()
- 5. 后置通知(org.springframework.aop.AfterReturningAdvice):在连接点正常完成后执行的通知
- 6. 环绕通知(org.aopalliance.intercept.MethodInterceptor):包围一个连接点的通知,最大特点是可以修改返回值,由于它在方法前后都加入了自己的逻辑代码,因此功能异常强大。
- 7. 异常通知(org.springframework.aop.ThrowsAdvice):这个通知会在方法抛出异常退出时执行
- 8. 适配器(org.springframework.aop.support.RegexpMethodPointcutAdvisor) 适配器=通知(Advice)+切入点(Pointcut)
- ==案例源代码(需要多多了解):==
1.连接点(Joinpoint):程序执行过程中明确的点,如方法的调用,或者异常的抛出.
2.目标(Target):被通知(被代理)的对象
3.通知(Advice):在某个特定的连接点上执行的动作,同时Advice也是程序代码的具体实现,例如一个实现日志记录的代码(通知有些书上也称为处理)
4.(重点)代理(Proxy):将通知应用到目标对象后创建的对象(代理=目标+通知),请注意:只有代理对象才有AOP功能,而AOP的代码是写在通知的方法里面的
例子:外科医生+护士
5.切入点(Pointcut):多个连接点的集合,定义了通知应该应用到那些连接点。
(也将Pointcut理解成一个条件 ,此条件决定了容器在什么情况下将通知和目标组合成代理返回给外部程序)
6.适配器(Advisor):适配器=通知(Advice)+切入点(Pointcut)
如何实现AOP
目标对象只负责业务逻辑代码
通知对象负责AOP代码,这二个对象都没有AOP的功能,只有代理对象才有
1. AOP
(理解)即面向切面编程
2. AOP带来的好处
让我们可以 “专心做事”
案例:
public void doSameBusiness (long lParam,String sParam){
// 记录日志
log.info(“调用 doSameBusiness方法,参数是:”+lParam);
// 输入合法性验证
if (lParam<=0){
throws new IllegalArgumentException(“xx应该大于0”);
}
if (sParam==null || sParam.trim().equals("")){
throws new IllegalArgumentException(“xx不能为空”);
}
// 异常处理
try{
…
}catch(…){
}catch(…){
}
// 事务控制
tx.commit();
}
给项目中所有类添加一个日志功能
BookServiceImpl源码:
package com.zking.test.p2;
//biz/service
//business
public class BookServiceImpl implements IBookService {
// private static final Logger log =
// LogManager.getLogger(BookServiceImpl.class);
public BookServiceImpl() {
super();
}
public boolean buy(String userName, String bookName, Double price) {
// log.info("userName={},bookName={},price={}", userName, bookName, price);
// 通过控制台的输出方式模拟购书
if (null == price || price <= 0) {
throw new PriceException("book price exception");
}
System.out.println(userName + " buy " + bookName + ", spend " + price);
return true;
}
public void comment(String userName, String comments) {
// 通过控制台的输出方式模拟发表书评
// log.info("userName={},comments={},price={}", userName, comments);
System.out.println(userName + " say:" + comments);
}
}
IBookService源码:
package com.zking.test.p2;
public interface IBookService {
// 购书
public boolean buy(String userName, String bookName, Double price);
// 发表书评
public void comment(String userName, String comments);
}
这样做合理吗?有效率吗?
3 工具类org.springframework.aop.framework.ProxyFactoryBean用来创建一个代理对象,在一般情况下它需要注入以下三个属性:
proxyInterfaces:代理应该实现的接口列表(List)
interceptorNames:需要应用到目标对象上的通知Bean的名字。(List)
target:目标对象 (Object)
代理对象的伪代码:
比如程序员写类:java–>编译–>.class–>类
而spring工具类:.class
$Proxy8实现了 IBookService接口
public class BookServiceImpl implements IBookService{}
//由spring工具类ProxyFactoryBean写的一个类
com.sun.proxy.$Proxy8
//实现了 IBookService接口
public class $Proxy8 implements IBookService{
//代理对象
IBookService target=bookServiceTarget;
//通知
String[] interceptorNames = new String[]{"myMethodBeforeAdvice"};
buy(a,b,c){
myMethodBeforeAdvice.before(....);
target.buy(a,b,c);
//myAfterReturningAdvice.afterReturning(....);
}
comment(){
}
}
new $Proxy8();
IBookService
BookServiceImpl $Proxy8
bookService.buy("张三", "火焰山", 88d);
$Proxy0.buy("张三", "火焰山", 88d)
4. 前置通知(org.springframework.aop.MethodBeforeAdvice):在连接点之前执行的通知()
案例:在购书系统当中使用AOP方式实现日志系统
5. 后置通知(org.springframework.aop.AfterReturningAdvice):在连接点正常完成后执行的通知
案例:在线购书系统中,要求不修改BookServiceImpl代码的情况下增加如下功能:对买书的用户进行返利:每买本书返利3元。(后置通知)
即:每调用一次buy方法打印:“[销售返利][时间]返利3元。”
6. 环绕通知(org.aopalliance.intercept.MethodInterceptor):包围一个连接点的通知,最大特点是可以修改返回值,由于它在方法前后都加入了自己的逻辑代码,因此功能异常强大。
它通过MethodInvocation.proceed()来调用目标方法(甚至可以不调用,这样目标方法就不会执行)
案例:修改日志系统不光要输出参数,还要输出返回值(环绕通知)
7. 异常通知(org.springframework.aop.ThrowsAdvice):这个通知会在方法抛出异常退出时执行
#这个接口里面没有定义方法,我们要求我们的类必须实现afterThrows这个方法
#public void afterThrowing( [Method method,] [Object args,] [Object target,] Throwable throwable );
#前面三个参数都是可选的,只有第三个参数是必须的,同时我们还可以在同一个类中定义这个方法的多个版本,如:
#public void afterThrowing( MyException1 ex ) {}
#public void afterThrowing( MyException2 ex ) {}
#具体那个方法被调用则根据具体的Exception来判断,由AOP容器自动识别 执行
案例: 书本价格为负数时抛出一个异常,通过异常通知取消此订单
创建PriceException类继承父类的所有异常方法
然后在创建PriceThrowsAdvice异常通知
配置到代理里面测试
8. 适配器(org.springframework.aop.support.RegexpMethodPointcutAdvisor) 适配器=通知(Advice)+切入点(Pointcut)
案例:通过适配器解决发书评时也返利的问题
.*buy
案例源代码(需要多多了解):
spring-p2.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"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
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-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 目标对象 -->
<bean id="bookServiceTarget" class="com.zking.test.p2.BookServiceImpl">
</bean>
<!-- 前置通知对象 -->
<bean id="myMethodBeforeAdivce" class="com.zking.test.p2.MyMethodBeforeAdivce">
</bean>
<!-- 后置通知对象 -->
<bean id="myAfterReturningAdvice" class="com.zking.test.p2.MyAfterReturningAdvice">
</bean>
<!-- 环绕通知对象 -->
<bean id="myMethodInterceptor" class="com.zking.test.p2.MyMethodInterceptor">
</bean>
<!-- 异常通知对象 -->
<bean id="priceThrowsAdvice" class="com.zking.test.p2.PriceThrowsAdvice">
</bean>
<!-- 适配器=通知(Advice)+切入点(Pointcut)-->
<bean id="regexpMethodPointcutAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<!-- 注入通知对象 -->
<property name="advice">
<ref bean="myAfterReturningAdvice"></ref>
</property>
<!-- 注入切入点对象 -->
<!-- 也就是正则验证 -->
<property name="patterns">
<list>
<value>.*buy</value>
</list>
</property>
</bean>
<!-- 代理=目标+通知 -->
<bean id="bookService" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 注入目标对象 -->
<property name="target">
<ref bean="bookServiceTarget"></ref>
</property>
<!-- 注入前置通知 加s是一个数组 -->
<property name="interceptorNames">
<list>
<value>myMethodBeforeAdivce</value>
<!-- <value>myAfterReturningAdvice</value> -->
<value>regexpMethodPointcutAdvisor</value>
<value>myMethodInterceptor</value>
<value>priceThrowsAdvice</value>
</list>
</property>
<!-- 代理应该实现的接口列表(List) -->
<property name="proxyInterfaces">
<list>
<value>com.zking.test.p2.IBookService</value>
</list>
</property>
</bean>
</beans>
测试Demo源码:
package com.zking.test.p2;
import org.springframework.aop.support.RegexpMethodPointcutAdvisor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Demo {
public static void main(String[] args) {
//指向spring.xml
ApplicationContext application = new ClassPathXmlApplicationContext("classpath:spring.xml");
//执行代理器
IBookService ibook = (IBookService) application.getBean("bookService");
ibook.buy("张三", "火焰山", 199d);
ibook.comment("张三", "这个书非常好看");
}
}