目录
在前面我们学习了Spring的IoC反转控制,利用Spring容器统一创建对象,接下来我们接着学习Spring的另一大内核AOP(Aspect Oriented Programming:面向切面编程)
一、AOP简介
1.1AOP
AOP 为 Aspect Oriented Programming 的缩写,意思为面向切面编程,是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
AOP 是 OOP(Object Oriented Programming:面向对象编程) 的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。
利用AOP可以对业务逻辑的各个部分进行隔离(解耦合),从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
假设我们此时要对数据库进行增删改操作,同时我们想对操作进行日志输出,那么我们会有三种方式去实现:
- 传统方法:直接在对应的方法里写日志输出的代码。该方法代码之间的耦合度较高,后期如果需要对日志输出进行修改,则要在每个功能模块都要修改,不推荐使用
- 抽取方法:对于上述问题,我们可以将日志方法抽取出来,供其他功能模块调用。后期如果需要对日志方法进行修改,只用在一个地方进行修改即可,该方法耦合度得到了降低。
- AOP:上述还有个问题,后期如果我们不想输出了,则还是要在对应的源码中修改,删除调用。而AOP则真正实现了解耦合,功能模块中不需要对日志方法进行调用,利用配置的形式,在程序运行期间,将功能模块中需要增强的方法和日志方法进行动态结合。
其作用和优势为:
- 作用:在程序运行期间,在不修改源码的情况下对方法进行功能增强
- 优势:减少重复代码,提高开发效率,并且便于维护
1.2AOP的底层实现
实际上,AOP 的底层是通过 Spring 提供的的动态代理技术实现的。
在运行期间,Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时先进行增强功能的介入,然后再去调用目标对象的方法,从而完成功能的增强。
简单来说,这里的增强功能就相当于日志输出功能,目标对象方法则对应增删改。
1.3AOP的动态代理技术
Spring底层使用的动态代理技术主要有以下两种,
- JDK 代理:基于接口的动态代理技术
- cglib 代理:基于父类的动态代理技术
我们创建一个新的maven工程spring_aop,然后分别用这两种技术实现动态代理。
1.3.1基于jdk的动态代理
jdl是基于接口的动态代理技术,目标对象和代理对象都有实现了相同的接口,所以首先我们新建一个目标对象接口,以及目标对象的实现,
interface TargetInterface {
public void save();
}
public class Target implements TargetInterface{
public void save() {
System.out.println("saving......");
}
}
然后是提供增强方法的增强对象,里面我们写一个前置增强和后置增强(这里是指和目标对象方法的执行顺序),
public class Advice {
public void before(){
System.out.println("前置增强......");
}
public void after(){
System.out.println("后置增强......");
}
}
然后我们新建一个代理的测试类,利用jdk接口技术进行动态代理,让Target的save方法也可以执行Advice的增强方法,
package proxy.jdk;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
final Target target=new Target();//创建目标对象(需要增强的对象)
final Advice advice=new Advice();//创建增强的对象(提供增强方法的对象)
TargetInterface proxy = (TargetInterface) Proxy.newProxyInstance(
target.getClass().getClassLoader(),//目标对象的类加载器(即Target.class)
target.getClass().getInterfaces(),//目标对象相同的接口字节码对象数组(即这里的TargetInterface)
new InvocationHandler() {
//调用代理对象的任何方法时,实质都会执行invoke方法
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
advice.before();//前置增强方法
Object invoke = method.invoke(target, args);//执行目标方法
advice.after();//后置增强方法
return invoke;//返回目标方法的返回值
}
}
);//返回值就是动态生成的代理对象,jdk是通过接口技术,所以返回对象为接口的实现类
proxy.save();//调用代理对象的方法
}
}
1.3.2基于cglib的动态代理
如果我们的目标对象没有接口,此时我们就可以使用cglib的方式进行动态代理。
cglib是第三方的库,早期的spring版本需要导jar包坐标,但是现在spring已经将cglib集成到spring-core中了,
所以我们可以导入spring的jar包后就可以直接使用(为了方便后续测试,我们也把junit一起导入),
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
首先我们还是创建目标对象,实现一个需要增强的方法,然后创建一个增强类,提供增强的方法,
class Target{
public void save() {
System.out.println("saving......");
}
}
class Advice {
public void before(){
System.out.println("前置增强......");
}
public void after(){
System.out.println("后置增强......");
}
}
然后我们使用cglib的方式,创建动态代理对象,对目标对象的方法进行增强,
package proxy.cglib;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class ProxyTest {
public static void main(String[] args) {
final Target target=new Target();//创建目标对象(需要增强的对象)
final Advice advice=new Advice();//创建增强的对象(提供增强方法的对象)
Enhancer enhancer=new Enhancer();//创建增强器
enhancer.setSuperclass(Target.class);//设置父类(目标对象)
//设置回调
enhancer.setCallback(new MethodInterceptor() {//调用代理对象的任何方法时,实质都会执行intercept方法
public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
advice.before();//前置增强方法
Object invoke = method.invoke(target, args);//执行目标的方法,参数为args
advice.after();//后置增强方法
return invoke;//返回目标方法的返回值
}
});
Target proxy = (Target) enhancer.create();//创建代理对象,此时代理对象的父级是Target类,所以返回值可以转换为Target类型
proxy.save();//调用代理对象的方法
}
}
1.4AOP相关概念
Spring 的 AOP 实现底层就是对上面的动态代理的代码进行了封装,封装后我们只需要对需要关注的部分进行代码编写,并通过配置的方式完成指定目标的方法增强。
在正式学习 AOP 的操作之前,我们必须理解 AOP 的相关术语,常用的术语如下:
- Target(目标对象):代理的目标对象
- Proxy (代理):一个类被 AOP 织入增强后,就产生一个结果代理类
- Joinpoint(连接点):所谓连接点是指那些被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点。所以我们要对目标对象的方法进行增强,则需要拦截这个方法,则可以被拦截的方法我们称为连接点。
- Pointcut(切入点):所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义。简单来说就是当连接点真正被拦截的时候,我们就称为这个连接点为切入点。(有些连接点可以被拦截,但是没有进行拦截增强)
- Advice(通知/增强):所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知
- Aspect(切面):是通知和切入点的结合
- Weaving(织入):是指把通知应用到目标对象来创建新的代理对象的过程。Spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入。
- 编译期织入:要求使用特殊的Java编译器
- 类装载器织入:要求使用特殊的类装载器
- 动态代理织入:在运行期为目标类添加增强生成子类的方式
1.5AOP开发明确的事项
1、需要编写的内容
- 编写核心业务代码(目标类的目标方法)
- 编写切面类,切面类中有通知(增强功能方法)
- 在配置文件中,配置织入关系,即将哪些通知与哪些连接点进行结合
2、AOP技术实现的内容
Spring 框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。
简单来说就是 Spring 会检测切入点方法,只要执行切入点方法,就会拦截进行增强,然后继续执行。
3、AOP底层使用的代理方式
在 Spring 中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。
如果目标对象有接口则使用 jdk 的方式进行动态代理,没有接口则使用 cglib 的方式进行代理。
二、基于XML的AOP开发
既然是通过配置的方式将通知和切入点进行结合,那么就可以有两种方式配置,一个是xml配置文件的形式,还有一个注解的方式。首先我们看看如何基于xml进行AOP开发。
2.1基于XML的AOP开发步骤
基于XML的AOP开发步骤如下:
- 导入 AOP 相关坐标
- 创建目标接口和目标类(内部有切点)
- 创建切面类(内部有增强方法)
- 将目标类和切面类的对象创建权交给 spring
- 在 applicationContext.xml 中配置织入关系
- 测试代码
其实 Spring 本身有一套AOP的配置方法,可以不用导入外部的AOP包坐标,
但是 AspectJ 对AOP的实现更好,所以我们用第三方的AOP包来配置织入关系,而不使用 Spring 内部的AOP实现。
第一步我们先导入AspectJ的AOP包坐标,
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
第二步我们创建目标接口和目标类,并且在类中实现方法
interface TargetInterface {
public void save();
}
class Target implements TargetInterface {
public void save() {
System.out.println("saving......");
}
}
第三步我们创建切面类,里面实现增强的方法,
class MyAspect {
public void before(){
System.out.println("前置增强......");
}
public void after(){
System.out.println("后置增强......");
}
}
第四步我们将目标类和切面类的对象创建权交给spring,所以我们创建 spring 配置文件进行配置,
<bean id="target" class="aop.xml.Target"></bean><!--目标对象-->
<bean id="myAspect" class="aop.xml.MyAspect"></bean><!--切面对象-->
第五步我们在 applicationContext.xml 文件中配置织入关系,
<!--配置织入关系:告诉spring框架哪些方法(切点)需要被加强,加强的方法(切面中的通知)有哪些-->
<aop:config>
<!--声明切面-->
<aop:aspect ref="myAspect">
<!--将aop.xml.MyAspect的before方法作为前置增强,增强的对象为aop.xml.Target的save方法-->
<aop:before method="before" pointcut="execution(public void aop.xml.Target.save())"></aop:before>
</aop:aspect>
</aop:config>
第六步我们创建一个测试类,测试代码,
import aop.xml.TargetInterface;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)//指定测试运行的类
@ContextConfiguration("classpath:applicationContext.xml")//指定配置文件路径
public class AOPTest {
@Autowired
private TargetInterface target;
@Test
public void test1(){
target.save();
}
}
2.2切点表达式的写法
在 applicationContext.xml 文件配置织入关系时,我们将aop.xml.MyAspect的before方法作为前置增强,增强的对象为aop.xml.Target的save方法,这里涉及到了切点表达式:
pointcut="execution(public void aop.xml.Target.save())"
一般的切点表达式语法为:
excution ( [修饰符] 返回值类型 包名.类名.方法名(参数) )
- 访问修饰符可以省略
- 返回值类型、包名、类名、方法名可以使用星号 * 代表任意
- 包名和类名之间一个点(".")代表当前包下的类,两个点("..")代表当前包及其子包下的类
- 参数列表可以使用两个点("..")表示任意个数、任意类型的参数列表
例如:
execution(public void aop.Target.method())//代表aop包下的Target类的method方法,并且该方法没有返回值和参数
execution(void aop.Target.*(..))//代表aop包下的Target类的所有返回值为void的方法
execution(* aop.*.*(..))//代表aop包下的所有类的所有方法
execution(* aop..*.*(..))//代表aop包及其子包下的所有类的所有方法
execution(* *..*.*(..))//代表所有包的所有类的所有方法
2.3通知的种类
我们之前写了一个前置加强的例子,
<aop:before method="before" pointcut="execution(* aop.xml.Target.*(..))"></aop:before>
一般的通知配置语法为:
<aop:通知类型 method="切面类中方法名" pointcut="切点表达式"></aop:通知类型>
通知的类型主要有以下几种:
名称 |
标签 |
说明 |
前置通知 |
<aop:before> |
用于配置前置通知。指定增强的方法在切入点方法之前执行 |
后置通知 |
<aop:after-returning> |
用于配置后置通知。指定增强的方法在切入点方法之后执行 |
环绕通知 |
<aop:around> |
用于配置环绕通知。指定增强的方法在切入点方法之前和之后都执行 |
异常抛出通知 |
<aop:throwing> |
用于配置异常抛出通知。指定增强的方法在出现异常时执行 |
最终通知 |
<aop:after> |
用于配置最终通知。无论增强方式执行是否有异常都会执行 |
我们首先在切面类中创建这些对应的通知方法,
public void before() {
System.out.println("前置增强......");
}
public void afterReturning() {
System.out.println("后置增强......");
}
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕前增强......");
Object proceed = proceedingJoinPoint.proceed();//执行切点的方法
System.out.println("环绕后增强......");
return proceed;
}
public void throwing() {
System.out.println("异常抛出增强......");
}
public void after() {
System.out.println("最终增强......");
}
然后在配置文件中配置织入关系,
<!--配置织入关系:告诉spring框架哪些方法(切点)需要被加强,加强的方法(切面中的通知)有哪些-->
<aop:config>
<!--声明切面-->
<aop:aspect ref="myAspect">
<aop:before method="before" pointcut="execution(public void aop.xml.Target.save())"></aop:before>
<aop:after-returning method="afterReturning" pointcut="execution(public void aop.xml.Target.save())"></aop:after-returning>
<aop:around method="around" pointcut="execution(public void aop.xml.Target.save())"></aop:around>
<aop:after-throwing method="throwing" pointcut="execution(public void aop.xml.Target.save())"></aop:after-throwing>
<aop:after method="after" pointcut="execution(public void aop.xml.Target.save())"></aop:after>
</aop:aspect>
</aop:config>
我们运行查看结果,
这里没有出现异常抛出,因为我们的目标类的方法没有异常,我们简单在save方法中加入异常 int i=1/0;,运行查看结果:
2.4切点表达式的抽取
在上面测试通知类型的时候,我们的切点都是一样的,
pointcut="execution(public void aop.xml.Target.save())"
所以我们可以简化代码,用一个id去标识这个切点表达式,让别人都去引用这个id即可,
当多个增强的切点表达式相同时,可以将切点表达式进行抽取,在增强中使用 pointcut-ref 属性代替 pointcut 属性来引用抽取后的切点表达式。
<aop:pointcut id="myPointcut" expression="execution(public void aop.xml.Target.save())"></aop:pointcut>
然后我们通过id来引用该切点表达式,
<aop:before method="before" pointcut-ref="myPointcut"></aop:before>
三、基于注解的AOP开发
3.1基于注解的AOP开发步骤
基于注解的AOP开发步骤如下:
- 导入 AOP 相关坐标
- 创建目标接口和目标类(内部有切点)
- 创建切面类(内部有增强方法)
- 将目标类和切面类的对象创建权交给 spring
- 在切面类中使用注解配置织入关系
- 在配置文件中开启组件扫描和AOP的自动代理
- 测试代码
第一步我们还是导入AOP相关坐标(之前xml导入过此时就不用导入了),
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
第二步是创建目标接口和目标类,
interface TargetInterface {
public void save();
}
class Target implements TargetInterface {
public void save() {
System.out.println("saving......");
}
}
第三步是创建切面类以及增强方法的实现,
class MyAspect {
public void before() {
System.out.println("前置增强......");
}
public void afterReturning() {
System.out.println("后置增强......");
}
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕前增强......");
Object proceed = proceedingJoinPoint.proceed();//执行切点的方法
System.out.println("环绕后增强......");
return proceed;
}
public void throwing() {
System.out.println("异常抛出增强......");
}
public void after() {
System.out.println("最终增强......");
}
}
第四步是将目标类和切面类的对象创建权交给Spring,之前我们通过xml配置,现在我们通过注解实现,并且通过注解告诉Spring哪一个类是切面类,
@Component("target")//在Spring容器中创建对应Bean对象
class Target implements TargetInterface {
...
}
@Component("myAspect")//在Spring容器中创建对应Bean对象
@Aspect//表明当前类为切面类
public class MyAspect {
...
}
第五步是在切面类中使用注解配置织入关系,
@Before(value = "execution(public void aop.annotation.TargetInterface.save())")//配置前置增强,切点表达式指定目标对象为TargetInterface类的save方法
public void before() {
System.out.println("前置增强......");
}
@AfterReturning("execution(* aop.annotation.*.*(..))")//配置后置增强,指定目标对象为aop.annotation包下的任意方法
public void afterReturning() {
System.out.println("后置增强......");
}
@Around("execution(* aop.annotation.*.*(..))")//配置环绕增强
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕前增强......");
Object proceed = proceedingJoinPoint.proceed();//执行切点的方法
System.out.println("环绕后增强......");
return proceed;
}
@AfterThrowing("execution(* aop.annotation.*.*(..))")//配置异常抛出增强
public void throwing() {
System.out.println("异常抛出增强......");
}
@After("execution(* aop.annotation.*.*(..))")//配置最终增强
public void after() {
System.out.println("最终增强......");
}
第六步是在配置文件中设置组件扫描和AOP的自动代理,这里可以用两种方式实现,一个是xml文件,一个是Spring核心配置类,
XML文件:需要导入aop和context对应的命名空间
<?xml version="1.0" encoding="UTF-8"?>
<!--先导入aop的命名空间-->
<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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--组件扫描-->
<context:component-scan base-package="aop.annotation"></context:component-scan>
<!--aop自动代理-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
Spring核心配置类(我觉得既然是注解方法就尽量不使用xml文件):
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration//标志该类是Spring的核心配置类
@ComponentScans({@ComponentScan("aop")})//配置组件扫描
@EnableAspectJAutoProxy//设置AOP自动代理
public class SpringConfiguration {
}
第七步是测试代码,
@RunWith(SpringJUnit4ClassRunner.class)//指定测试运行的类
@ContextConfiguration(classes = SpringConfiguration.class)//指定Spring核心配置类
//如果第六步用的是xml文件配置则这里改为xml文件的路径@ContextConfiguration("classpath:applicationContext-Annotation.xml")//指定配置文件路径
public class AOPAnnotationTest {
@Autowired
private TargetInterface target;
@Test
public void test1(){
target.save();
}
}
3.2注解通知的类型
这个其实和xml通知的类型差不多,都是那几种,只不过表现方式不同,
通知配置的语法为:@通知注解("切点表达式")
通知名称 |
注解标识 |
备注 |
前置通知 |
@Before |
用于配置前置通知。指定增强的方法在切入点方法之前执行 |
后置通知 |
@AfterReturning |
用于配置后置通知。指定增强的方法在切入点方法之后执行 |
环绕通知 |
@Around |
用于配置环绕通知。指定增强的方法在切入点方法之前和之后都执行 |
异常抛出通知 |
@AfterThrowing |
用于配置异常抛出通知。指定增强的方法在出现异常时执行 |
最终通知 |
@After |
用于配置最终通知。无论增强方式执行是否有异常都会执行 |
上述我们其实已经进行代码测试了。
3.3注解的切点表达式抽取
同 xml 配置 aop 一样,我们可以将切点表达式抽取。
抽取方式是在切面内定义方法,在该方法上使用 @Pointcut 注解定义切点表达式,然后在增强注解中进行引用。具体如下:
//在方法上定义切面表达式
@Pointcut(value = "execution(* aop.annotation.*.*(..))")
public void myPoint(){}
//通过方法名引用切面表达式
@Before("MyAspect.myPoint()")//配置前置增强
public void before() { System.out.println("前置增强......");}