本期内容:
1、aop介绍
2、前置通知
3、后置通知
4、环绕通知
5、异常通知
6、过滤通知
一、aop介绍
1、AOP中关键性概念
连接点(Joinpoint):程序执行过程中明确的点,入方法的调用,或者异常的抛出。
目标(Target):被通知(被代理)的对象。——注1:完成具体的业务逻辑。
通知(Advice):在某个特点的连接点上执行的动作,同时Advice也是程序代码的具体实现,例如一个实现被通知(被代理)的对象。——注1:完成具体的业务逻辑。
代理(Proxy):将通知应用到目标对象后创建的对象(代理=目标+通知)。例子:外科医生+护士——注3:只有代理对象才有AOP功能,而AOP的代码是写在通知的方法里面的。
切入点(Pointcut):多个连接点的集合,定义了通知应该应用到那些连接点。(也将Pointcut理解成一个条件,此条件决定了容器在什么情况下将通知和目标组合成代理返回给外部程序)
适配器(Advisor):适配器=通知(Advice)+切入点(Pointcut)
示例图:
2、如何实现AOP
目标对象只负责业务逻辑代码
通知对象负责AOP代码,这二个对象都没有AOP的功能,只有代理对象才有
通知类型 实现接口 应用场景
前置通知 实现org.springframework.aop.MethodBeforeAdvice接口 买书、评论前加系统日志
后置通知 实现org.springframework.aop.AfterReturningAdvice接口 买书返利
环绕通知 实现org.aopalliance.intercept.MethodInterceptor接口 类似拦截器,会包括切入点,目标类前后都会执行代码
异常通知 实现org.springframework.aop.ThrowsAdvice接口 出现异常执行系统提示,然后进行处理。价格异常为例
过滤通知(适配器) 实现org.springframework.aop.support.RegexpMethodPointcutAdvisor接口 处理买书返利的bug
二、准备工作及用到的工具类
接口类IBookBiz:
package com.zxy.aop.biz;
public interface IBookBiz {
// 购书
public boolean buy(String userName, String bookName, Double price);
// 发表书评
public void comment(String userName, String comments);
}
接口类IBookBiz的实现类BookBizImpl:
package com.zxy.aop.biz.imp;
import com.zxy.aop.biz.IBookBiz;
import com.zxy.aop.exception.PriceException;
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);
}
}
异常通知所需的运行时异常PriceException类:
package com.zxy.aop.exception;
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);
}
}
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="userBiz1" class="com.zxy.ioc.biz.impl.UserBizImpl"></bean>
<bean name="userBiz2" class="com.zxy.ioc.biz.impl.UserBizImpl2"></bean>
<bean name="personAction" class="com.zxy.ioc.web.PersonAction">
<property name="userBiz" ref="userBiz2"></property>
</bean>
<bean name="userAction" class="com.zxy.ioc.web.UserAction"></bean>
<bean name="paramAction" class="com.zxy.ioc.web.ParamAction">
<!-- 1.set传参-->
<!-- <property name="name" value="高级人"></property>
<property name="age" value="18"></property>
<property name="hobby" >
<list>
<value>打滴滴</value>
<value>踩小溜</value>
</list>
</property> -->
<constructor-arg name="name" value="高级人2"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
<constructor-arg name="hobby" >
<list>
<value>打滴滴1</value>
<value>踩小溜1</value>
</list>
</constructor-arg>
</bean>
<!--目标 -->
<bean name="bookBiz" class="com.zxy.aop.biz.imp.BookBizImpl"></bean>
<!--前置通知 -->
<bean name="myBefore" class="com.zxy.aop.advice.MyMethodBeforeAdvice"></bean>
<!--后置通知 -->
<bean name="myAfter" class="com.zxy.aop.advice.MyAfterReturningAdvice"></bean>
<!--环绕通知 -->
<bean name="myFilterAdvice" class="com.zxy.aop.advice.MyMethodInterceptor"></bean>
<!--异常通知 -->
<bean name="myExceptionAdvice" class="com.zxy.aop.advice.MyThrowsAdvice"></bean>
<!--过滤通知 -->
<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>
</list>
</property>
</bean>
<!--生成代理对象 (目标+通知)-->
<bean class="org.springframework.aop.framework.ProxyFactoryBean"
id="proxyFactoryBean">
<!--ref 目标对象 -->
<property name="target" ref="bookBiz"></property>
<!-- 代理工厂生产的代理需要实现的接口列表 -->
<property name="proxyInterfaces">
<list>
<value>com.zxy.aop.biz.IBookBiz</value>
</list>
</property>
<!--绑定的那些通知 -->
<property name="interceptorNames">
<list>
<value>myBefore</value>
<!-- <value>myAfter</value> -->
<value>myFilterAdvice</value>
<value>myAfter2</value>
<value>myExceptionAdvice</value>
</list>
</property>
</bean>
</beans>
测试类AopTest.java:
package com.zxy.aop.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.zxy.aop.biz.IBookBiz;
public class AopTest {
public static void main(String[] args) {
//获取到spring-context.xml的配置文件
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/spring-context.xml");
IBookBiz bookBiz = (IBookBiz) applicationContext.getBean("bookBiz");
bookBiz.buy("晓哥", "《金瓶梅》", 99.9);
bookBiz.comment("晓哥", "yyds ");
}
}
三、前置通知
前置通知MyMethodBeforeAdvice (要实现MethodBeforeAdvice接口):
package com.zxy.aop.advice;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.springframework.aop.MethodBeforeAdvice;
/**
* 前置通知
*
* 调用项目中的某一接口实现类的方式时,将类名.方法名,携带的参数,作为日志存储到数据库。
* target:目标对象
* method:被触发的目标对象的方法
* args:目标对象的目标方法携带的参数
* @author Administrator
*
*/
public class MyMethodBeforeAdvice implements MethodBeforeAdvice {
public void before(Method method, Object[] args, Object target) throws Throwable {
String targetName = target.getClass().getName();
String methodName = method.getName();
String params = Arrays.toString(args);
String msg = "【系统日志】:正在调用->"+targetName+"."+methodName+",携带的参数:"+params;
System.out.println(msg);
}
}
使用前置通知需先进行配置,和一些改动(配置和改动如下)spring-context.xml
运行结果: 拿到代理对象:
四、后置通知
后置通知MyAfterReturningAdvice (要实现AfterReturningAdvice接口):相比于前置多了一个参数,返回值
价值:事务提交,关闭session
package com.zxy.aop.advice;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.springframework.aop.AfterReturningAdvice;
/**
* 后置通知
* @author Administrator
*
*/
public class MyAfterReturningAdvice implements AfterReturningAdvice {
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);
}
}
配置spring-context.xml
调用测试AopTest.java
执行结果又不一样,先走前置通知,再走目标对象,再走后置对象
前置通知与后置通知能让你专注于业务代码
五、环绕通知
价值:包含了前置通知与后置通知
MyMethodInterceptor:
package com.zxy.aop.advice;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* 环绕通知
* @author Administrator
*
*/
public class MyMethodInterceptor implements MethodInterceptor {
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);
//invocation可以执行被代理的目标对象的业务方法
Object returnValue = invocation.proceed();
String msg2 = "【环绕通知】:目标对象所调用的方法的返回值:" + returnValue;
System.out.println(msg2);
return returnValue;
}
}
进行配置:
<!-- 环绕通知 -->
<bean name="myFilterAdvice" class="com.zxy.aop.advice.MyMethodInterceptor"></bean>
<!-- 生成代理(目标对象+通知) -->
<bean class="org.springframework.aop.framework.ProxyFactoryBean"
id="proxyFactoryBean">
<!-- 目标对象 -->
<property name="target" ref="bookBiz"></property>
<!-- 代理工厂生产的代理需要实现的接口列表 -->
<property name="proxyInterfaces">
<list>
<value>com.zxy.aop.biz.IBookBiz</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>myBefore</value>
<value>myAfter</value>
<value>myFilterAdvice</value>
</list>
</property>
</bean>
运用测试代码, 呈现结果:
六、异常通知
假如出现异常,会直接终止程序,不会在进行数据回滚
异常通知MyThrowsAdvice(要实现ThrowsAdvice接口):(要么同时成功,要么同时失败。
package com.zxy.aop.advice;
import org.springframework.aop.ThrowsAdvice;
import com.zxy.aop.exception.PriceException;
/**
* 异常通知
* 一定要实现这个接口
* 一定要叫这个方法名
* @author Administrator
*
*/
public class MyThrowsAdvice implements ThrowsAdvice {
public void afterThrowing( PriceException ex ) {
System.out.println("价格输入有误,购买失败,请重新输入!!!");
}
}
<!-- 异常通知 -->
<bean name="myExceptionAdvice" class="com.zxy.aop.advice.MyThrowsAdvice"></bean>
<!-- 生成代理(目标对象+通知) -->
<bean class="org.springframework.aop.framework.ProxyFactoryBean"
id="proxyFactoryBean">
<!-- 目标对象 -->
<property name="target" ref="bookBiz"></property>
<!-- 代理工厂生产的代理需要实现的接口列表 -->
<property name="proxyInterfaces">
<list>
<value>com.zxy.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>
对测试类AopTest.java 进行修改,制造异常数据(-99.9)
package com.zxy.aop.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.zxy.aop.biz.IBookBiz;
public class AopTest {
public static void main(String[] args) {
//获取到spring-context.xml的配置文件
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/spring-context.xml");
IBookBiz bookBiz = (IBookBiz) applicationContext.getBean("proxyFactoryBean");
bookBiz.buy("晓哥", "《金瓶梅》", -99.9);
bookBiz.comment("晓哥", "yyds");
}
}
运行结果如下(会有提示,出现解决方案)
七、过滤缓存
过滤通知:并不是每个方法都需要通知,所有需要过滤一下
配置spring-context.xml(过滤通知替代后置通知)
<!-- 过滤通知 -->
<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 class="org.springframework.aop.framework.ProxyFactoryBean"
id="proxyFactoryBean">
<!-- 目标对象 -->
<property name="target" ref="bookBiz"></property>
<!-- 代理工厂生产的代理需要实现的接口列表 -->
<property name="proxyInterfaces">
<list>
<value>com.zxy.aop.biz.IBookBiz</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>myBefore</value>
<!-- <value>myAfter</value> -->
<value>myAfter2</value>
<value>myFilterAdvice</value>
<value>myExceptionAdvice</value>
</list>
</property>
</bean>
测试原有代码:
结束啦