看完上一篇博客,大致入门了Spring,对于DI(依赖注入)、IOC(控制反转)有了一定的认识。这篇博客,我们还要继续学习Spring。现在,由Spring的另一个核心 — — AOP开始学习。
1.AOP
1.1APO介绍
1.1.1什么是AOP
- 在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP(面向对象编程)的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
- AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码
- 经典应用:事务管理、性能监视、安全检查、缓存 、日志等
- Spring AOP使用纯Java实现,不需要专门的编译过程和类加载器,在运行期通过代理方式向目标类织入增强代码
- AspectJ是一个基于Java语言的AOP框架,Spring2.0开始,Spring AOP引入对Aspect的支持,AspectJ扩展了Java语言,提供了一个专门的编译器,在编译时提供横向代码的织入
举个例子吧,这里有一堆的service类,UserService、MenuService、CompanyService...,现在我要求你让每一个service的方法执行前开启事物,执行后关闭提交,但又不能改变原本service类的代码。没学过动态代理和AOP思想之前,我们本能的会去分别写一个类去继承UserService、MenuService、CompanyService....在这些子类的每一个方法中,写事务的开启提交。先不说这么写,作用的类其实已经不是原本的对象了。况且这么多的service类,一个一个写,代码重复率不是一点点的高。所以,我们要学习动态代理,深刻理解AOP面向切面编程。
我们可以将事务的开启提交写到一个类中,假设是A类。我们希望A类的这些代码都能作用到UserService中的那些方法上,所以我们想到了代理。代理类将得到A和UserService中的方法开始代理。后文我们用代码一步步模拟。
理解AOP,必须先理解动态代理的概念,如果对这方面感觉有些陌生的朋友,可以进入我的主页,有篇专门介绍JAVA动态代理,其中提及了AOP面向切面编程思想,但是比较浅薄,所以这篇博文将会重点介绍Sring中的AOP。
1.1.2AOP实现原理
- aop底层将采用代理机制进行实现。
- 当有接口 + 实现类时:spring采用 jdk 的动态代理Proxy。
- 当只有实现类:spring 采用 cglib字节码增强。
1.1.3AOP术语(必须掌握)
1.target:目标类,需要被代理的类。例如:UserService
2.Joinpoint(连接点):所谓连接点是指那些可能被拦截到的方法。例如:所有的方法(你可以理解为公共卫生间中的那些坑)
3.PointCut 切入点:已经被增强的连接点。例如:addUser()(你可以理解为公共卫生间中正在被使用的坑)
4.advice 通知/增强,增强的代码。例如:after、before
5.Weaving(织入):是指把增强advice应用到目标对象target来创建新的代理对象proxy的过程.
6.proxy 代理类
7.Aspect(切面): 是切入点pointcut和通知advice的结合
一个线是一个特殊的面。
一个切入点和一个通知,组成成一个特殊的面。
对于Aspect(切面)的概念,如果你理解不了,那么请听我说。A中的方法是advice,UserService中的一些方法是PointCut,advice和pointCut(这些方法)都会被weaving(织入)Proxy(代理类),我们可以看做这个时候,advice和pointCut这两个点相连,连成了一条线,当advice和pointCut越来越多,这里有越来越多的连线,便组成了一个面(其实数学的理论上,三个点就已经可以确定一个平面了,就算只有一个advice与ponitCut想连,一条直线,在数学的定义里,一个线是一个特殊的面。)就是我们的Aspect(切面)。说了这么多,对于AOP面向切面编程,是不是有了一些感受了呢?
1.2手动方式实现代理
1.2.1JDK动态代理
- JDK动态代理 对“装饰者”设计模式简化。使用前提:必须有接口
我们可以来模拟一下:
1.目标类:接口 + 实现类
2.切面类:用于存通知 MyAspect
3.工厂类:编写工厂生成代理
4.测试
/**
* 目标类
* @author Keo.Zhao
*
*/
public interface UserService {
public void addUser();
public void updateUser();
public void deleteUser();
}
/**
* 目标类的实现类
* @author Keo.Zhao
*
*/
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("com.spring.proxy.jdk:addUser");
}
@Override
public void updateUser() {
System.out.println("com.spring.proxy.jdk:updateUser");
}
@Override
public void deleteUser() {
System.out.println("com.spring.proxy.jdk:deleteUser");
}
}
/**
* 切面类
* @author Keo.Zhao
*
*/
public class MyAspect {
public void before(){
System.out.println("我是前方法");
}
public void after(){<span style="font-family:SimSun;">
</span>
System.out.println("我是后方法");
}
}
然后是最重要的工厂类
public class MyBeanFactory {
public static UserService createService(){
//1 目标类
final UserService userService = new UserServiceImpl();
//2切面类
final MyAspect myAspect = new MyAspect();
/* 3 代理类:将目标类(切入点)和 切面类(通知) 结合 --> 切面
* Proxy.newProxyInstance
* 参数1:loader ,类加载器,动态代理类 运行时创建,任何类都需要类加载器将其加载到内存。
* 一般情况:当前类.class.getClassLoader();
* 目标类实例.getClass().get...
* 参数2:Class[] interfaces 代理类需要实现的所有接口
* 方式1:目标类实例.getClass().getInterfaces() ;注意:只能获得自己接口,不能获得父元素接口
* 方式2:new Class[]{UserService.class}
* 例如:jdbc 驱动 --> DriverManager 获得接口 Connection
* 参数3:InvocationHandler 处理类,接口,必须进行实现类,一般采用匿名内部
* 提供 invoke 方法,代理类的每一个方法执行时,都将调用一次invoke
* 参数31:Object proxy :代理对象
* 参数32:Method method : 代理对象当前执行的方法的描述对象(反射)
* 执行方法名:method.getName()
* 执行方法:method.invoke(对象,实际参数)
* 参数33:Object[] args :方法实际参数
*
*/
UserService proxService = (UserService)Proxy.newProxyInstance(
MyBeanFactory.class.getClassLoader(),
userService.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//前执行
myAspect.before();
//执行目标类的方法
Object obj = method.invoke(userService, args);
//后执行
myAspect.after();
return obj;
}
});
return proxService;
}
}
测试类
@Test
public void testJDK() throws Exception {
UserService userService = MyBeanFactory.createUserService();
userService.addUser();
userService.updateUser();
}
1.2.2CGLIB
- 没有接口,只有实现类。
- 采用字节码增强框架 cglib,在运行时 创建目标类的子类,从而对目标类进行增强。
- 导入jar包:
自己导包:
核心:hibernate-distribution-3.6.10.Final\lib\bytecode\cglib\cglib-2.2.jar
依赖:struts-2.3.15.3\apps\struts2-blank\WEB-INF\lib\asm-3.3.jar
spring-core..jar已经整合以上两个内容
改动较大的只有工厂类,直接看示例代码:
public class MyBeanFactory {
public static UserServiceImpl createService(){
//1 目标类
final UserServiceImpl userService = new UserServiceImpl();
//2切面类
final MyAspect myAspect = new MyAspect();
// 3.代理类 ,采用cglib,底层创建目标类的子类
//3.1 核心类
Enhancer enhancer = new Enhancer();
//3.2 确定父类
enhancer.setSuperclass(userService.getClass());
/* 3.3 设置回调函数 , MethodInterceptor接口 等效 jdk InvocationHandler接口
* intercept() 等效 jdk invoke()
* 参数1、参数2、参数3:以invoke一样
* 参数4:methodProxy 方法的代理
*
*
*/
enhancer.setCallback(new MethodInterceptor(){
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
//前
myAspect.before();
//执行目标类的方法
Object obj = method.invoke(userService, args);
// * 执行代理类的父类 ,执行目标类 (目标类和代理类 父子关系)
methodProxy.invokeSuper(proxy, args);
//后
myAspect.after();
return obj;
}
});
//3.4 创建代理
UserServiceImpl proxService = (UserServiceImpl) enhancer.create();
return proxService;
}
}
1.3AOP联盟通知类型
- AOP联盟为通知Advice定义了org.aopalliance.aop.Advice
- Spring按照通知Advice在目标类方法的连接点位置,可以分为5类
• 前置通知 org.springframework.aop.MethodBeforeAdvice
• 在目标方法执行前实施增强
• 后置通知 org.springframework.aop.AfterReturningAdvice
• 在目标方法执行后实施增强
• 环绕通知 org.aopalliance.intercept.MethodInterceptor
• 在目标方法执行前后实施增强
•异常抛出通知 org.springframework.aop.ThrowsAdvice
•在方法抛出异常后实施增强
• 引介通知 org.springframework.aop.IntroductionInterceptor
•在目标类中添加一些新的方法和属性可以这么理解:
环绕通知,必须手动执行目标方法 try{ //前置通知 //执行目标方法 //后置通知 } catch(){ //抛出异常通知 } |
1.4.Spring编写代理:半自动
- 让spring 创建代理对象,从spring容器中手动的获取代理对象。
- 导入jar包:
核心:4+1
AOP:AOP联盟(规范)、spring-aop (实现)
目标类
public interface UserService {
public void addUser();
public void updateUser();
public void deleteUser();
}
切面类
/**
* 切面类中确定通知,需要实现不同接口,接口就是规范,从而就确定方法名称。
* * 采用“环绕通知” MethodInterceptor
*
*/
public class MyAspect implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
System.out.println("前3");
//手动执行目标方法
Object obj = mi.proceed();
System.out.println("后3");
return obj;
}
}
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
<!-- 创建目标类 -->
<bean id="userServiceId" class="com.spring.proxy.factoryBean.UserServiceImpl"></bean>
<!-- 创建切面类 -->
<bean id="myAspectId" class="com.spring.proxy.factoryBean.MyAspect"></bean>
<!-- 3 创建代理类
* 使用工厂bean FactoryBean ,底层调用 getObject() 返回特殊bean
* ProxyFactoryBean 用于创建代理工厂bean,生成特殊代理对象
interfaces : 确定接口们
通过<array>可以设置多个值
只有一个值时,value=""
target : 确定目标类
interceptorNames : 通知 切面类的名称,类型String[],如果设置一个值 value=""
optimize :强制使用cglib
<property name="optimize" value="true"></property>
底层机制
如果目标类有接口,采用jdk动态代理
如果没有接口,采用cglib 字节码增强
如果声明 optimize = true ,无论是否有接口,都采用cglib
-->
<bean id="proxyServiceId" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interfaces" value="com.itheima.b_factory_bean.UserService"></property>
<property name="target" ref="userServiceId"></property>
<property name="interceptorNames" value="myAspectId"></property>
</bean>
</beans>
测试类
@Test
public void demo01(){
String xmlPath = "com/spring/proxy/factoryBean/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//获得代理类
UserService userService = (UserService) applicationContext.getBean("proxyServiceId");
userService.addUser();
userService.updateUser();
userService.deleteUser();
}
1.5Spring编写代理:全自动
- 从spring容器获得目标类,如果配置aop,spring将自动生成代理。
- 要确定目标类,使用aspectj 切入点表达式,导入jar包
spring-framework-3.0.2.RELEASE-dependencies\org.aspectj\com.springsource.org.aspectj.weaver\1.6.8.RELEASE
相比较半自动,别的地方基本上没有什么改动,变化主要是在Spring的配置文件。
首先:创建目标类和切面类
<!-- 1.创建目标类 -->
<bean id="userServiceId" class="com.spring.proxy.spring_Aop.UserServiceImpl"></bean>
<!-- 2.创建切面类 -->
<bean id="myAspectId" class="com.spring.proxy.spring_Aop.MyAspect"></bean>
然后,就是我们的AOP编程了。开始AOP编程之前,我们应该先导入一个命名空间,参见官方文档(xsd-config.html):
于是我们得到如下命名空间
然后,我们就可以开始使用 <aop:config>进行配置
proxy-target-class="true" 声明时使用cglib代理
<aop:pointcut> 切入点 ,从目标对象获得具体方法
<aop:advisor> 特殊的切面,只有一个通知 和 一个切入点
advice-ref 通知引用
pointcut-ref 切入点引用
再写上切入点表达式。(这里看不懂没有关系,后文会详细介绍接入点表达式,这是一个很重要的知识点)
所以配置文件如下:
<p><span style="color:#08080;"><</span><span style="color:#3f7f7f;background:rgb(192,192,192);">beans</span> <span style="color:#7f07f;">xmlns</span><span style="color:#000000;">=</span><em><span style="color:#2a0ff;">"http://www.springframework.org/schema/beans"</span></em></p><p> <span style="color:#7f07f;">xmlns:xsi</span><span style="color:#000000;">=</span><em><span style="color:#2a0ff;">"http://www.w3.org/2001/XMLSchema-instance"</span></em></p><p> <span style="color:#7f07f;">xmlns:context</span><span style="color:#000000;">=</span><em><span style="color:#2a0ff;">"http://www.springframework.org/schema/context"</span></em></p><p> <span style="color:#7f07f;">xmlns:aop</span><span style="color:#000000;">=</span><em><span style="color:#2a0ff;">"http://www.springframework.org/schema/aop"</span></em></p><p> <span style="color:#7f07f;">xsi:schemaLocation</span><span style="color:#000000;">=</span><em><span style="color:#2a0ff;">"http://www.springframework.org/schema/beans </span></em></p><p><em><span style="color:#2a0ff;"> </span><span style="color:#2a0ff;"> http://www.springframework.org/schema/beans/spring-beans.xsd</span></em></p><p><em><span style="color:#2a0ff;"> </span><span style="color:#2a0ff;"> http://www.springframework.org/schema/aop </span></em></p><p><em><span style="color:#2a0ff;"> </span><span style="color:#2a0ff;"> http://www.springframework.org/schema/aop/spring-aop.xsd</span></em></p><p><em><span style="color:#2a0ff;"> </span><span style="color:#2a0ff;"> http://www.springframework.org/schema/context </span></em></p><p><em><span style="color:#2a0ff;"> </span><span style="color:#2a0ff;"> http://www.springframework.org/schema/context/spring-context.xsd"</span></em><span style="color:#08080;">></span></p>
<!-- 1.创建目标类 -->
<bean id="userServiceId" class="com.spring.proxy.spring_Aop.UserServiceImpl"></bean>
<!-- 2.创建切面类 -->
<bean id="myAspectId" class="com.spring.proxy.spring_Aop.MyAspect"></bean>
<!-- 3 aop编程
3.1 导入命名空间
3.2 使用 <aop:config>进行配置
proxy-target-class="true" 声明时使用cglib代理
<aop:pointcut> 切入点 ,从目标对象获得具体方法
<aop:advisor> 特殊的切面,只有一个通知 和 一个切入点
advice-ref 通知引用
pointcut-ref 切入点引用
3.3 切入点表达式
execution(* com.itheima.c_spring_aop.*.*(..))
选择方法 返回值任意 包 类名任意 方法名任意 参数任意
-->
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* com.spring.proxy.spring_Aop.*.*(..))" id="myPointCut"/>
<aop:advisor advice-ref="myAspectId" pointcut-ref="myPointCut"/>
</aop:config>
</beans>
测试类
@Test
public void demo01(){
String xmlPath = "com/spring/proxy/spring_Aop/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//获得目标类
UserService userService = (UserService) applicationContext.getBean("userServiceId");
userService.addUser();
userService.updateUser();
userService.deleteUser();
}
2.AspectJ
2.1介绍
- AspectJ是一个基于Java语言的AOP框架
- Spring2.0以后新增了对AspectJ切点表达式支持
- @AspectJ 是AspectJ1.5新增功能,通过JDK5注解技术,允许直接在Bean类中定义切面
- 主要用途:自定义开发
2.2切入点表达式
1.execution() 用于描述方法
语法:execution(修饰符 返回值 包.类.方法名(参数) throws异常)
修饰符,一般省略
public 公共方法
* 任意
返回值,不能省略
void 返回没有值
String 返回值字符串
* 任意
包,[可以省略]
eg:
com.spring.crm 固定包
com.spring.crm.*.service 指的是crm包下面子包任意 (例如:com.spring.crm.staff.service)
com.spring.crm.. crm包下面的所有子包(含自己)
com.spring.crm.*.service.. crm包下面任意子包,固定目录service,service目录任意包
类,[可以省略]
UserServiceImpl 指定类
*Impl 以Impl结尾
User* 以User开头
* 任意
方法名,不能省略
addUser 固定方法
add* 以add开头
*Do 以Do结尾
* 任意
(参数)
() 无参
(int) 一个整型
(int ,int) 两个
(..) 参数任意
throws ,可省略,一般不写。
综合例子:
综合1
execution(* com.sping.crm.*.service..*.*(..))
综合2
<aop:pointcut expression="execution(* com.spring.*WithCommit.*(..)) ||
execution(* com.spring.*Service.*(..))" id="myPointCut"/>
2.within:匹配包或子包中的方法(了解)
within(com.spring.aop..*)
3.this:匹配实现接口的代理对象中的方法(了解)
this(com.spring.aop.user.UserDAO)
4.target:匹配实现接口的目标对象中的方法(了解)
target(com.spring.aop.user.UserDAO)
5.args:匹配参数格式符合标准的方法(了解)
args(int,int)
6.bean(id):对指定的bean所有的方法(了解)
bean('userServiceId')
2.3AspectJ 通知类型
-
aop联盟定义通知类型,具有特性接口,必须实现,从而确定方法名称。
-
aspectj 通知类型,只定义类型名称。已经方法格式。
-
个数:6种,知道5种,掌握1中。
before:前置通知(应用:各种校验)
在方法执行前执行,如果通知抛出异常,阻止方法运行
afterReturning:后置通知(应用:常规数据处理)
方法正常返回后执行,如果方法中抛出异常,通知无法执行
必须在方法执行后才执行,所以可以获得方法的返回值。
around:环绕通知(应用:十分强大,可以做任何事情)
方法执行前后分别执行,可以阻止方法的执行
必须手动执行目标方法
afterThrowing:抛出异常通知(应用:包装异常信息)
方法抛出异常后执行,如果方法没有抛出异常,无法执行
after:最终通知(应用:清理现场,相当于finally)
方法执行完毕后执行,无论方法中是否出现异常
环绕
try{ //前置:before //手动执行目标方法 //后置:afterRetruning } catch(){ //抛出异常 afterThrowing } finally{ //最终 after } |
对应着底层的实现类:
我们可以随意看两个加深一下上述的印象:
2.4导入JAR包
- 4个:
aop联盟规范
spring aop 实现
aspect 规范
spring aspect 实现
3.5基于XML的实现
1.目标类:接口 +实现(还是使用之前的Uservice和UserServiceImpl)
2.切面类:编写多个通知,采用aspectj通知名称任意(方法名任意)
3.aop编程,将通知应用到目标类
4.测试
public class TestAspectXml {
@Test
public void testAspectXml() throws Exception {
String xmlPath = "com/spring/aspect_xml/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserService userService = (UserService) applicationContext.getBean("userServiceId");
userService.addUser();
userService.deleteUser();
userService.updateUser();
}
}
因为通知方式有很多种,切面类和AOP编程的配置我从这里开始分开来写:
前置通知:<aop:before method="" pointcut="" pointcut-ref=""/>
method : 通知,及方法名
pointcut :切入点表达式,此表达式只能当前通知使用。
pointcut-ref : 切入点引用,可以与其他通知共享切入点。
通知方法格式:public void myBefore(JoinPoint joinPoint)
参数1:org.aspectj.lang.JoinPoint 用于描述连接点(目标方法),获得目标方法名等
切面类:
public void myBefore(JoinPoint joinPoint){
System.out.println("前置通知 : " + joinPoint.getSignature().getName());
}
配置XML:
<!-- 1 创建目标类 -->
<bean id="userServiceId" class="com.spring.aspect_xml.UserServiceImpl"></bean>
<!-- 2 创建切面类(通知) -->
<bean id="myAspectId" class="com.spring.aspect_xml.MyAspect"></bean>
<aop:config>
<aop:aspect ref="myAspectId">
<aop:pointcut expression="execution(* com.spring.aspect_xml.UserServiceImpl.*(..))" id="myPointCut"/>
<span style="font-family:宋体;"> <aop:before method="myBefore" pointcut-ref="myPointCut"/></span>
</aop:aspect>
</aop:config>
后置通知:目标方法后执行,获得返回值
<aop:after-returning method="" pointcut-ref="" returning=""/>
returning 通知方法第二个参数的名称
通知方法格式:public void myAfterReturning(JoinPoint joinPoint,Object ret){
参数1:连接点描述
参数2:类型Object,参数名 returning="ret" 配置的
切面类:
public void myAfterReturning(JoinPoint joinPoint,Object ret){
System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret);
}
配置XML
<!-- 1 创建目标类 -->
<bean id="userServiceId" class="com.spring.aspect_xml.UserServiceImpl"></bean>
<!-- 2 创建切面类(通知) -->
<bean id="myAspectId" class="com.spring.aspect_xml.MyAspect"></bean>
<aop:config>
<aop:aspect ref="myAspectId">
<aop:pointcut expression="execution(* com.spring.aspect_xml.UserServiceImpl.*(..))" id="myPointCut"/>
<aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="ret" />
</aop:aspect>
</aop:config>
环绕通知
<aop:around method="" pointcut-ref=""/>
通知方法格式:public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
返回值类型:Object
方法名:任意
参数:org.aspectj.lang.ProceedingJoinPoint
抛出异常
执行目标方法:Object obj = joinPoint.proceed();
切面类:
public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("前");
//手动执行目标方法
Object obj = joinPoint.proceed();
System.out.println("后");
return obj;
}
配置XML
<pre name="code" class="html"><!-- 1 创建目标类 -->
<bean id="userServiceId" class="com.spring.aspect_xml.UserServiceImpl"></bean>
<!-- 2 创建切面类(通知) -->
<bean id="myAspectId" class="com.spring.aspect_xml.MyAspect"></bean>
<aop:config>
<aop:aspect ref="myAspectId">
<aop:pointcut expression="execution(* com.spring.aspect_xml.UserServiceImpl.*(..))" id="myPointCut"/>
<aop:around method="myAround" pointcut-ref="myPointCut"/>
</aop:aspect>
</aop:config>
抛出异常:<aop:after-throwing method="" pointcut-ref="" throwing=""/> throwing :通知方法的第二个参数名称 通知方法格式:public void myAfterThrowing(JoinPoint joinPoint,Throwable e) 参数1:连接点描述对象 参数2:获得异常信息,类型Throwable ,参数名由throwing="e" 配置
切面类:
public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
System.out.println("抛出异常通知 : " + e.getMessage());
}
配置XML:
<pre name="code" class="html"><!-- 1 创建目标类 -->
<bean id="userServiceId" class="com.spring.aspect_xml.UserServiceImpl"></bean>
<!-- 2 创建切面类(通知) -->
<bean id="myAspectId" class="com.spring.aspect_xml.MyAspect"></bean>
<aop:config>
<aop:aspect ref="myAspectId">
<aop:pointcut expression="execution(* com.spring.aspect_xml.UserServiceImpl.*(..))" id="myPointCut"/>
<aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointCut" throwing="e"/>
</aop:aspect>
</aop:config>
最终通知:与前置类似
切面类:
public void myAfter(JoinPoint joinPoint){
System.out.println("最终通知");
}
配置XML
<pre name="code" class="html"><!-- 1 创建目标类 -->
<bean id="userServiceId" class="com.spring.aspect_xml.UserServiceImpl"></bean>
<!-- 2 创建切面类(通知) -->
<bean id="myAspectId" class="com.spring.aspect_xml.MyAspect"></bean>
<aop:config>
<aop:aspect ref="myAspectId">
<aop:pointcut expression="execution(* com.spring.aspect_xml.UserServiceImpl.*(..))" id="myPointCut"/>
<p><span style="color:#08080;"> <</span><span style="color:#3f7f7f;">aop:after</span> <span style="color:#7f07f;">method</span><span style="color:#000000;">=</span><em><span style="color:#2a0ff;">"myAfter"</span></em> <span style="color:#7f07f;">pointcut-ref</span><span style="color:#000000;">=</span><em><span style="color:#2a0ff;">"myPointCut"</span></em><span style="color:#08080;">/></span>
</p> </aop:aspect>
</aop:config>
最后贴一下完整的代码:
切面类:
/**
* 切面类,含有多个通知
* @author Keo.Zhao
*
*/
public class MyAspect {
public void myBefore(JoinPoint joinPoint){
System.out.println("前置通知 : " + joinPoint.getSignature().getName());
}
public void myAfterReturning(JoinPoint joinPoint,Object ret){
System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret);
}
public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("前");
//手动执行目标方法
Object obj = joinPoint.proceed();
System.out.println("后");
return obj;
}
public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
System.out.println("抛出异常通知 : " + e.getMessage());
}
public void myAfter(JoinPoint joinPoint){
System.out.println("最终通知");
}
}
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">
<!-- 1 创建目标类 -->
<bean id="userServiceId" class="com.spring.aspect_xml.UserServiceImpl"></bean>
<!-- 2 创建切面类(通知) -->
<bean id="myAspectId" class="com.spring.aspect_xml.MyAspect"></bean>
<!-- 3 aop编程
<aop:aspect> 将切面类 声明“切面”,从而获得通知(方法)
ref 切面类引用
<aop:pointcut> 声明一个切入点,所有的通知都可以使用。
expression 切入点表达式
id 名称,用于其它通知引用
-->
<aop:config>
<aop:aspect ref="myAspectId">
<aop:pointcut expression="execution(* com.spring.aspect_xml.UserServiceImpl.*(..))" id="myPointCut"/>
<!-- 3.1 前置通知
<aop:before method="" pointcut="" pointcut-ref=""/>
method : 通知,及方法名
pointcut :切入点表达式,此表达式只能当前通知使用。
pointcut-ref : 切入点引用,可以与其他通知共享切入点。
通知方法格式:public void myBefore(JoinPoint joinPoint){
参数1:org.aspectj.lang.JoinPoint 用于描述连接点(目标方法),获得目标方法名等
例如:
<aop:before method="myBefore" pointcut-ref="myPointCut"/>
-->
<!-- 3.2后置通知 ,目标方法后执行,获得返回值
<aop:after-returning method="" pointcut-ref="" returning=""/>
returning 通知方法第二个参数的名称
通知方法格式:public void myAfterReturning(JoinPoint joinPoint,Object ret){
参数1:连接点描述
参数2:类型Object,参数名 returning="ret" 配置的
例如:
<aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="ret" />
-->
<!-- 3.3 环绕通知
<aop:around method="" pointcut-ref=""/>
通知方法格式:public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
返回值类型:Object
方法名:任意
参数:org.aspectj.lang.ProceedingJoinPoint
抛出异常
执行目标方法:Object obj = joinPoint.proceed();
例如:
<aop:around method="myAround" pointcut-ref="myPointCut"/>
-->
<!-- 3.4 抛出异常
<aop:after-throwing method="" pointcut-ref="" throwing=""/>
throwing :通知方法的第二个参数名称
通知方法格式:public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
参数1:连接点描述对象
参数2:获得异常信息,类型Throwable ,参数名由throwing="e" 配置
例如:
<aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointCut" throwing="e"/>
-->
<!-- 3.5 最终通知 -->
<aop:after method="myAfter" pointcut-ref="myPointCut"/>
</aop:aspect>
</aop:config>
</beans>
3.6基于注解
基于注解的实现,可以参考XML配置的逐步改造。注解实现是我们开发中使用的方式,一定要掌握。
package com.spring.aspect_anno;
import org.springframework.stereotype.Service;
/**
* 目标类的实现类
* @author Keo.Zhao
*
*/
@Service("userServiceId")
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("com.spring.aspect_anno:addUser");
}
@Override
public void updateUser() {
System.out.println("com.spring.aspect_anno:updateUser");
}
@Override
public void deleteUser() {
System.out.println("com.spring.aspect_anno:deleteUser");
}
}
切面类:
package com.spring.aspect_anno;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* 切面类,含有多个通知
* @author Keo.Zhao
*
*/
@Component
@Aspect //声明切面
public class MyAspect {
//@Before("execution(* com.spring.aspect_anno.UserServiceImpl.*(..))")
public void myBefore(JoinPoint joinPoint){
System.out.println("前置通知 : " + joinPoint.getSignature().getName());
}
//声明公共切入点表达式
@Pointcut("execution(* com.spring.aspect_anno.UserServiceImpl.*(..))")
private void myPointCut(){
}
//@AfterReturning(value="myPointCut()" ,returning="ret")
public void myAfterReturning(JoinPoint joinPoint,Object ret){
System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret);
}
@Around(value="myPointCut()")
public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("前");
//手动执行目标方法
Object obj = joinPoint.proceed();
System.out.println("后");
return obj;
}
//@AfterThrowing(value="myPointCut()",throwing="e")
public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
System.out.println("抛出异常通知 : " + e.getMessage());
}
//@After("myPointCut()")
public void myAfter(JoinPoint joinPoint){
System.out.println("最终通知");
}
}
配置文件:
<?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:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1.扫描 注解类 -->
<context:component-scan base-package="com.spring.aspect_anno"></context:component-scan>
<!-- 2.确定 aop注解生效 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
AOP注解配置总结:
@Aspect 声明切面,修饰切面类,从而获得 通知。
通知
@Before 前置
@AfterReturning 后置
@Around 环绕
@AfterThrowing 抛出异常
@After 最终
切入点
@PointCut ,修饰方法 private void xxx(){} 之后通过“方法名”获得切入点引用
经过这篇博客的学习,我们深入了AOP编程思想,学习了AspectJ,spring的知识点已经掌握了大半,下一篇博客,我们还将继续学习Spring,谈谈JdbcTemplate、事务管理还有Sprin中的一些整合。