一、AOP中关键性概念
连接点(Joinpoint):程序执行过程中明确的点,如方法的调用,或者异常的抛出.
目标(Target):被通知(被代理)的对象 注1:完成具体的业务逻辑
通知(Advice):在某个特定的连接点上执行的动作,同时Advice也是程序代码的具体实现,例如一个实现日志记录的代码(通知有些书上也称为处理) 注2:完成切面编程
代理(Proxy):将通知应用到目标对象后创建的对象(代理=目标+通知), 例子:外科医生+护士 注3:只有代理对象才有AOP功能,而AOP的代码是写在通知的方法里面的
切入点(Pointcut):多个连接点的集合,定义了通知应该应用到那些连接点。 (也将Pointcut理解成一个条件 ,此条件决定了容器在什么情况下将通知和目标组合成代理返回给外部程序) 适配器(Advisor):适配器=通知(Advice)+切入点(Pointcut)
3 工具类org.springframework.aop.framework.ProxyFactoryBean用来创建一个代理对象,在一般情况下它需要注入以下三个属性:
proxyInterfaces:代理应该实现的接口列表(List)
interceptorNames:需要应用到目标对象上的通知Bean的名字。
(List) target:目标对象 (Object)
如何实现AOP
AOP 即面向切面编程
目标对象只负责业务逻辑代码 通知对象负责AOP代码,这二个对象都没有AOP的功能,只有代理对象才有
二、前置通知
前置通知的价值在于:创建session,开启事务
在连接点之前执行的通知() 案例:在购书系统当中使用AOP方式实现日志系统
IBookBiz
package com.dhm.aop.Biz;
public interface IBookBiz {
// 购书
public boolean buy(String userName, String bookName, Double price);
// 发表书评
public void comment(String userName, String comments);
}
PriceException继承RuntimeException
package com.dhm.aop.Biz;
public class PriceException extends RuntimeException {
public PriceException() {
super();
}
public PriceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public PriceException(String message, Throwable cause) {
super(message, cause);
}
public PriceException(String message) {
super(message);
}
public PriceException(Throwable cause) {
super(cause);
}
}
MyMethodBeforeAdvice实现MethodBeforeAdvice
target:目标对象
method:被触发的目标对象的方法
args:目标对象的目标方法的携带的参数
package com.dhm.aop.Biz;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.springframework.aop.MethodBeforeAdvice;
/**
* 买书,评论前加系统日志
* @author zjjt
*
*/
public class MyMethodBeforeAdvice implements MethodBeforeAdvice{
@Override
public void before(Method method, Object[] arg1, Object target) throws Throwable {
String clzName=target.getClass().getName();
String methodName=method.getName();
String params=Arrays.toString(arg1);
System.out.println("【系统日志】:正在调用"+clzName+"."+methodName+"("+params+")");
}
}
BookBizImpl实现IBookBiz
package com.dhm.aop.Biz;
public class BookBizImpl implements IBookBiz {
public BookBizImpl() {
super();
}
public boolean buy(String userName, String bookName, Double 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) {
// 通过控制台的输出方式模拟发表书评
System.out.println(userName + " say:" + comments);
}
}
spring-context.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"
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">
<!--
本文件中配置整个项目中包含的javabean,目的在于spring统一管理
-->
<bean name="UserBiz" class="com.dhm.ioc.Biz.UserBizimpl"></bean>
<!-- <bean name="userBiz2" class="com.dhm.ioc.Biz.UserBizimpl2"></bean> -->
<bean name="personAction" class="com.dhm.ioc.web.PersonAction">
<property name="UserBiz" ref="UserBiz"></property>
</bean>
<bean name="userAction" class="com.dhm.ioc.web.UserAction"></bean>
<bean name="userAction2" class="com.dhm.ioc.web.UserAction2"></bean>
<bean name="paramAction" class="com.dhm.ioc.entity.ParamAction">
<constructor-arg name="name" value="dhm"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
<constructor-arg name="hobby">
<list>
<value>吃</value>
<value>喝</value>
</list>
</constructor-arg>
</bean><!-- ****************************************Aop -->
<!-- 目标对象 -->
<bean id="bookBiz" class="com.dhm.aop.Biz.BookBizImpl"></bean>
<!-- 通知 -->
<bean id="myBefore" class="com.dhm.aop.Biz.MyMethodBeforeAdvice"></bean>
<!-- 有代理工厂来组装目标对象及通知 -->
<bean id="bookProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="bookBiz"></property>
<property name="proxyInterfaces">
<list>
<value>com.dhm.aop.Biz.IBookBiz</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>myBefore</value>
</list>
</property>
</bean>
</beans>
测试及结果
package com.dhm.aop.Biz;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class AopTest {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/spring-context.xml");
IBookBiz bookBiz=(IBookBiz) applicationContext.getBean("bookProxy");// 这个buy是先去获取前置通知的代码,再去调用目标对象的业务代码
bookBiz.buy("小戴", "小米的余生", 22.4d);
bookBiz.comment("小戴", "给我整不会了");
} }
三、后置通知
后置通知一般放在方法结尾,比前置通知多了一个返回值
后置通知价值在于:提交事务,关闭session
在连接点正常完成后执行的通知 案例:在线购书系统中,要求不修改BookBizImpl代码的情况下增加如下功能:对买书的用户进行返利:每买本书返利3元。(后置通知) 即:每调用一次buy方法打印:“销售返利返利3元。”
spring-context.xml
<!-- 后置通知 -->
<bean id="myAfter" class="com.dhm.aop.Biz.MyAfterReturningAdvice"></bean>
<!-- 有代理工厂来组装目标对象及通知 -->
<bean id="bookProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="bookBiz"></property>
<property name="proxyInterfaces">
<list>
<value>com.dhm.aop.Biz.IBookBiz</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>myBefore</value>
<value>myAfter</value>
</list>
</property>
</bean>
MyAfterReturningAdvice 实现AfterReturningAdvice
package com.dhm.aop.Biz;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.springframework.aop.AfterReturningAdvice;
public class MyAfterReturningAdvice implements AfterReturningAdvice{
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
String targetName = target.getClass().getName();
String methodName = method.getName();
String params = Arrays.toString(args);
String msg = "【返利通知:返利3元】:正在调用->" + targetName + "." + methodName + ",携带的参数:" + params + ";目标对象所调用的方法的返回值:"
+ returnValue;
System.out.println(msg);
}
}
四、环绕通知
包含了前置和后置
包围一个连接点的通知,最大特点是可以修改返回值,由于它在方法前后都加入了自己的逻辑代码,因此功能异常强大。 它通过MethodInvocation.proceed()来调用目标方法(甚至可以不调用,这样目标方法就不会执行)
案例:修改日志系统不光要输出参数,还要输出返回值(环绕通知)
spring-context.xml
<!--环绕通知 -->
<bean name="myFilterAdvice" class="com.dhm.aop.Biz.MyMethodInterceptor"></bean><!-- 有代理工厂来组装目标对象及通知 -->
<bean id="bookProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="bookBiz"></property>
<property name="proxyInterfaces">
<list>
<value>com.dhm.aop.Biz.IBookBiz</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>myBefore</value>
<value>myAfter</value>
<value>myFilterAdvice</value>
</list>
</property>
</bean>
MyMethodInterceptor 实现MethodInterceptor
package com.dhm.aop.Biz;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MyMethodInterceptor implements MethodInterceptor{
// invocation:可以执行被代理的目标对象的业务方法
public Object invoke(MethodInvocation invocation) throws Throwable {
Object target = invocation.getThis();
Method method = invocation.getMethod();
Object[] args = invocation.getArguments();
// a.jsp window.open(b.jsp)
// b.jsp xxx->返回object->b.jsp window.close();window.getArguments;
String targetName = target.getClass().getName();
String methodName = method.getName();
String params = Arrays.toString(args);
String msg = "【环绕通知】:正在调用->" + targetName + "." + methodName + ",携带的参数:" + params;
System.out.println(msg);
Object returnValue = invocation.proceed();
String msg2 = "【环绕通知】:目标对象所调用的方法的返回值:" + returnValue;
System.out.println(msg2);
return returnValue;
}
}
五、异常通知
这个通知会在方法抛出异常退出时执行
案例: 书本价格为负数时抛出一个异常,通过异常通知取消此订单
spring-context.xml
<!--异常通知 -->
<bean name="myExceptionAdvice" class="com.dhm.aop.Biz.MyThrowsAdvice"></bean>
<!-- 有代理工厂来组装目标对象及通知 -->
<bean id="bookProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="bookBiz"></property>
<property name="proxyInterfaces">
<list>
<value>com.dhm.aop.Biz.IBookBiz</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>myBefore</value>
<value>myAfter</value>
<value>myFilterAdvice</value>
<value>myExceptionAdvice</value>
</list>
</property>
</bean>
MyThrowsAdvice 实现 ThrowsAdvice
package com.dhm.aop.Biz;
import org.springframework.aop.ThrowsAdvice;
/**
* 一定要实现这个接口
* 一定要叫这个方法名
* @author zjjt
*
*/
public class MyThrowsAdvice implements ThrowsAdvice{
public void afterThrowing( PriceException ex ) {
System.out.println("价格输入有误,购买失败,请重新输入!!!");
}
}
将价格改为负数,进入异常通知
六、过滤通知
spring-context.xml
过滤具有后置通知的buy方法、del方法
<!-- 过滤通知 -->
<bean class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"
id="myAfter2">
<property name="advice" ref="myAfter"></property>
<!-- .*buy:[.*]任意字符0~n个,以buy结尾的方法 -->
<!-- <property name="pattern" value=".*buy"></property> -->
<property name="patterns">
<list>
<value>.*buy</value>
<value>.*del</value>
</list>
</property>
</bean>
<!-- 有代理工厂来组装目标对象及通知 -->
<bean id="bookProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="bookBiz"></property>
<property name="proxyInterfaces">
<list>
<value>com.dhm.aop.Biz.IBookBiz</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>myBefore</value>
<value>myAfter</value>
<value>myFilterAdvice</value>
<value>myExceptionAdvice</value>
<value>myAfter2</value>
</list>
</property>
</bean>
---------------------没有了--------------------------------------------