一、AOP的引入
这里可以把单个模块当做是一圆柱,假如没有aop,在做日志处理的时候,我们会在每个模块中添加日志或者权限处理,日志或权限类似圆柱体的部分圆柱。

一般大多数的日志或权限处理代码是相同的,为了实现代码复用,我们可能把日志处理抽离成一个新的方法。

但是这样我们仍然必须手动插入这些方法,而且这两个方法就是强耦合的,假如此时我们不需要这个功能了,或者想换成其他功能,那么就必须一个个修改。
通过动态代理,可以在指定位置执行对应流程。这样就可以将一些横向的功能抽离出来形成一个独立的模块,然后在指定位置插入这些功能。这样的思想,被称为面向切面编程,亦即AOP。

二、AOP主要概念
上小节介绍了引入AOP的好处,本小节来了解下AOP的几个核心概念。
1.横切关注点
AOP把一个业务流程分成几部分,例如权限检查、业务处理、日志记录,每个部分单独处理,然后把它们组装成完整的业务流,每部分被称为切面或关注点。
2.切面
类是对物体特征的抽象,切面就是对横切关注点的抽象。可以每部分抽象成一叠纸一样一层一层的,那每张纸都是一切面。
3.连接点
被拦截到的点,因为Spring只支持方法类型的连接点,所以在Spring中连接点指的就是被拦截到的方法,实际上连接点还可以是字段或者构造器.其实Spring只支持方法类型的连接点就包含字段和构造器。为啥呢?因为字段它是通过get,set方法,构造器它其实也是方法。Spring只支持方法类型的连接点和连接点是字段或者构造器它们是包含关系。
4.切入点
对连接点进行拦截的定义,连接点可以很多,但并不一定每个连接点都进行操作,比如莲藕,藕段与藕段之间它们是有连接点的,但不一定都切开。
5.通知
通知指的就是指拦截到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类,这个有点类似把藕段与藕段断开之后要做的事情,是往里面加蜂蜜还是做什么。
6.目标对象
代理的目标对象,就是动态代理的target,在实际操作中一般会先实现AOP的接口,然后配置这些接口作用到哪些对象上,被作用的对象就是目标对象。
7.织入
切面是独立的,目标对象也是独立的,它们是不耦合的,那它怎么把切面放到目标对象中呢,这时就需要进行织入操作,就类似一中的,怎么把target和打印日志联系到一起呢,那就需要动态代理,在spring中aop.framework.ProxyFactory就是用作织入器,来进行横切逻辑的织入。
8.引入
不改代码的同时,为类动态的添加方法或字段。
三、AOP实现
前面小节主要介绍了AOP的理论知识,本小节通过示例进一步理解Spring中AOP的使用。主要介绍AOP的三种实现方式:经典的基于代理的AOP、AspectJ基于XML的配置、AspectJ基于注解的配置。
一、经典的基于代理的AOP
基于代理的AOP主要介绍MethodBeforeAdvice、AfterReturningAdvice、ThrowsAdvice三个接口的使用。
MethodBeforeAdvice:见名知意,通过方法名就可以猜到是它的作用。方法前拦截器在执行指定方法前调用,参数分别为被调用的方法、执行时被传入的参数、被拦截的bean。
AfterReturningAdvice:返回后拦截器在执行完指定方法并返回之后调用。如果有返回值可以获取到返回值,否则为null。参数分别为方法返回值、被调用的方法、执行时被传入的参数、被拦截的bean。
ThrowsAdvice:异常拦截器在指定方法抛出异常时被调用。该接口并未定义方法,因此不需要实现任何方法。那它是怎么拦截的呢?我们可以查看该接口的定义,在定义类文档中有如下图的说明。如果在实现该接口的类中定义了如public void afterThrowing(Exception ex)、public void afterThrowing(Method method, Object[] args, Object target, Exception ex)方法抛出异常时就会被调用。

在软件开发中推荐面向接口的编程,所以这里创建了一个IAOPServices接口,并定义了两个方法。withAopMethod方法将使用拦截器拦截的方法,withNoAopMethod方法不会被拦截器拦截。接口代码如下:
1package basicAop; 2 3public interface IAOPServices { 4 5 public String withAopMethod() throws Exception; 6 7 public String withNoAopMethod() throws Exception; 8 9}
在AOPServicesImpl类中实现了该接口,并在该类中定义了String类型的description属性,以及对应的getter、setter方法。两个接口方法将返回该description属性的值。

1package basicAop; 2 3public class AOPServicesImpl implements IAOPServices { 4 5 private String description; 6 public String getDescription() { 7 return description; 8 } 9 10 public void setDescription(String description) { 11 this.description = description; 12 } 13 14 public String withAopMethod() throws Exception { 15 System.out.println("AOP函数运行方法:withAopMethod"); 16 if(description.trim().length()==0){ 17 throw new Exception("description属性不能为空"); 18 } 19 return description; 20 } 21 22 public String withNoAopMethod() throws Exception { 23 System.out.println("无AOP函数运行方法:withNoAopMethod"); 24 return description; 25 } 26}
View Code
上面把要使用AOP拦截的方法准备好了,下面就是定义AOP拦截器方法了。这里在AOPInterceptor类中实现了上面的AfterReturningAdvice,MethodBeforeAdvice,ThrowsAdvice三个接口。

1package basicAop; 2 3import java.lang.reflect.Method; 4 5import org.springframework.aop.AfterReturningAdvice; 6import org.springframework.aop.MethodBeforeAdvice; 7import org.springframework.aop.ThrowsAdvice; 8 9public class AOPInterceptor implements AfterReturningAdvice,MethodBeforeAdvice,ThrowsAdvice { 10 11 public void afterReturning(Object value, Method method, Object[] args, Object instance) throws Throwable { 12 13 System.out.println("方法"+method.getName()+"运行结束,返回值为:"+value); 14 } 15 16 public void before(Method method, Object[] args, Object instance) throws Throwable { 17 System.out.println("执行MethodBeforeAdvice,即将执行的方法:"+method.getName()); 18 if(instance instanceof AOPServicesImpl) 19 { 20 String description=((AOPServicesImpl)instance).getDescription(); 21 if(description==null) 22 { 23 throw new NullPointerException("description属性不能为null"); 24 } 25 } 26 } 27 public void afterThrowing(Exception ex){ 28 System.out.println("抛出了异常:"+ex.getMessage()); 29 } 30 31 public void afterThrowing(Method method, Object[] args, Object target, Exception ex){ 32 System.out.println("方法"+method.getName()+"抛出了异常:"+ex.getMessage()); 33 } 34}
View Code
这里要拦截的方法和拦截器都准备好了,那怎么将该拦截器用于拦截该方法呢?这里就需要进行配置。首先在pom.xml中引入依赖,这里引入spring-aop、spring-context。

1<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 2 <modelVersion>4.0.0</modelVersion> 3 <groupId>com.demo</groupId> 4 <artifactId>BasicAOP</artifactId> 5 <version>0.0.1-SNAPSHOT</version> 6 <properties> 7 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 8 <spring.version>5.0.0.RELEASE</spring.version> 9 </properties> 10<dependencies> 11 <dependency> 12 <groupId>org.springframework</groupId> 13 <artifactId>spring-context</artifactId> 14 <version>${spring.version}</version> 15 </dependency> 16 <dependency> 17 <groupId>org.springframework</groupId> 18 <artifactId>spring-aop</artifactId> 19 <version>${spring.version}</version> 20 </dependency> 21</dependencies> 22</project>
View Code
实际上Spring无法将Services实现类与拦截器直接组装,因为没有对应的setter、getter方法。安装时借助 Spring中的代理类,将自定义拦截器注入到NameMatchMethodPointcutAdvisor类中的advice属性中,再将定义好的NameMatchMethodPointcutAdvisor对象注入到ProxyFactoryBean。这里将自定义的AOPInterceptor拦截器注入到NameMatchMethodPointcutAdvisor中,然后将NameMatchMethodPointcutAdvisor对象注入到ProxyFactoryBean中。

1<?xml version="1.0" encoding="UTF-8"?> 2<beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context.xsd 10 http://www.springframework.org/schema/aop 11 http://www.springframework.org/schema/aop/spring-aop.xsd"> 12 13 <bean id="aopInterceptor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor"> 14 <property name="advice"> 15 <bean class="basicAop.AOPInterceptor"></bean> 16 </property> 17 <property name="mappedName" value="withAopMethod"></property> 18 </bean> 19 20 <bean id="aopService" class="org.springframework.aop.framework.ProxyFactoryBean"> 21 <property name="interceptorNames"> 22 <list> 23 <value>aopInterceptor</value> 24 </list> 25 </property> 26 <property name="target"> 27 <bean class="basicAop.AOPServicesImpl"> 28 <property name="description" value="basicAop"></property> 29 </bean> 30 </property> 31 </bean> 32 </beans>
View Code
从Spring容器中获取IAOPServices对象,并分别执行IAOPServices中的两个方法。Spring会在withAopMethod()方法前后添加拦截器,在withNoAopMethod()方法前后并不会添加。

1package basicAop; 2 3import org.springframework.beans.factory.BeanFactory; 4import org.springframework.context.ApplicationContext; 5import org.springframework.context.support.ClassPathXmlApplicationContext; 6 7 8 9public class AopTest { 10 11 public static void main(String[] args) throws Exception { 12 13 ApplicationContext context=new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}); 14 BeanFactory factory=context; 15 IAOPServices services=(IAOPServices)context.getBean("aopService"); 16 services.withAopMethod(); 17 services.withNoAopMethod(); 18 } 19}
View Code
运行结果如下:

二、AspectJ基于XML的配置
AspectJ是一个面向切面的框架,它扩展了Java语言。AspectJ定义了AOP语法,所以它有一个专门的编译器用来生成遵守Java字节编码规范的Class文件。我们还是利用IAOPServices接口、AOPServicesImpl类实现AspectJ基于XML的AOP编程。下表是AspectJ主要的配置元素。使用AspectJ时需要引入两个依赖项aopalliance、aspectjweaver。在引入这两个依赖项时需要注意,有时报错误,更新下两个依赖项的版本就好了。

1<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 2 <modelVersion>4.0.0</modelVersion> 3 <groupId>com.demo</groupId> 4 <artifactId>AutoScanAOP</artifactId> 5 <version>0.0.1-SNAPSHOT</version> 6 <properties> 7 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 8 <spring.version>5.0.0.RELEASE</spring.version> 9 </properties> 10 11 <dependencies> 12 <dependency> 13 <groupId>org.springframework</groupId> 14 <artifactId>spring-context</artifactId> 15 <version>${spring.version}</version> 16 </dependency> 17 <dependency> 18 <groupId>org.springframework</groupId> 19 <artifactId>spring-core</artifactId> 20 <version>${spring.version}</version> 21 </dependency> 22 <dependency> 23 <groupId>org.springframework</groupId> 24 <artifactId>spring-beans</artifactId> 25 <version>${spring.version}</version> 26 </dependency> 27 <dependency> 28 <groupId>org.springframework</groupId> 29 <artifactId>spring-aop</artifactId> 30 <version>${spring.version}</version> 31 </dependency> 32 <dependency> 33 <groupId>aopalliance</groupId> 34 <artifactId>aopalliance</artifactId> 35 <version>1.0</version> 36 </dependency> 37 <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> 38 <dependency> 39 <groupId>org.aspectj</groupId> 40 <artifactId>aspectjweaver</artifactId> 41 <version>1.8.11</version> 42 </dependency> 43 </dependencies> 44</project>
View Code
AOP配置元素
描述
顶层的AOP配置元素,大多数的aop:\*元素必须包含在aop:config元素内
定义切面
启用@AspectJ注解驱动的切面
定义切点
定义AOP通知器
定义AOP前置通知
定义AOP后置通知(不管被通知的方法是否执行成功)
定义成功返回后的通知
定义抛出异常后的通知
定义AOP环绕通知
为被通知的对象引入额外的接口,并透明地实现
这里定义了XMLAdvice拦截器方法,用于演示前置、后置、成功返回、异常返回、环绕通知。

1package Services; 2 3 4import org.aspectj.lang.JoinPoint; 5import org.aspectj.lang.ProceedingJoinPoint; 6 7public class XMLAdvice { 8 public void beforeAdvice() { 9 System.out.println("前置通知执行了"); 10 } 11 12 public void afterAdvice() { 13 System.out.println("后置通知执行了"); 14 } 15 16 public void afterReturnAdvice(String result) { 17 System.out.println("返回通知执行了" + "运行业务方法返回的结果为" + result); 18 } 19 20 public String aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { 21 String result = ""; 22 try { 23 System.out.println("环绕通知开始执行了"); 24 long start = System.currentTimeMillis(); 25 result = (String) proceedingJoinPoint.proceed(); 26 long end = System.currentTimeMillis(); 27 System.out.println("环绕通知执行结束了"); 28 System.out.println("执行业务方法共计:" + (end - start) + "毫秒。"); 29 } catch (Throwable e) { 30 31 } 32 return result; 33 } 34 35 public void throwingAdvice(JoinPoint joinPoint, Exception e) { 36 StringBuffer stringBuffer = new StringBuffer(); 37 stringBuffer.append("异常通知执行了."); 38 stringBuffer.append("方法:").append(joinPoint.getSignature().getName()).append("出现了异常."); 39 stringBuffer.append("异常信息为:").append(e.getMessage()); 40 System.out.println(stringBuffer.toString()); 41 } 42 43}
View Code
上面把拦截器定义完成,之后就是把定义好的拦截器与Services关联在一起。使用AOP配置元素将Services与拦截器中的方法关联上。

1<?xml version="1.0" encoding="UTF-8"?> 2<beans xmlns="http://www.springframework.org/schema/beans" 3xmlns:context="http://www.springframework.org/schema/context" 4xmlns:mvc="http://www.springframework.org/schema/mvc" 5xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 6xmlns:aop="http://www.springframework.org/schema/aop" 7xsi:schemaLocation=" 8http://www.springframework.org/schema/beans 9http://www.springframework.org/schema/beans/spring-beans.xsd 10http://www.springframework.org/schema/context 11http://www.springframework.org/schema/context/spring-context.xsd 12http://www.springframework.org/schema/mvc 13http://www.springframework.org/schema/mvc/spring-mvc.xsd 14http://www.springframework.org/schema/aop 15http://www.springframework.org/schema/aop/spring-aop.xsd 16"> 17 18<bean id="serviceImplA" class="Services.AOPServicesImpl"> 19 <property name="description" value="basicAop"></property> 20</bean> 21<bean id="serviceAspectBean" class="Services.XMLAdvice" /> 22<aop:config> 23 <aop:aspect id="serviceAspect" ref="serviceAspectBean"> 24 <aop:pointcut id="servicePointcut" expression="execution(* Services.*.withAop*(..))" /> 25 <aop:before pointcut-ref="servicePointcut" method="beforeAdvice" /> 26 <aop:after pointcut-ref="servicePointcut" method="afterAdvice" /> 27 <aop:after-returning pointcut-ref="servicePointcut" method="afterReturnAdvice" returning="result" /> 28 <aop:around pointcut-ref="servicePointcut" method="aroundAdvice" /> 29 <aop:after-throwing pointcut-ref="servicePointcut" method="throwingAdvice" throwing="e" /> 30 </aop:aspect> 31</aop:config> 32</beans>
View Code
配置完之后还是和经典的基于代理的AOP一样,运行代码从Spring容器中获取IAOPServices对象,并分别执行IAOPServices中的两个方法。Spring会在withAopMethod()方法前后添加拦截器,在withNoAopMethod()方法前后并不会添加。

1package AspectJAOP; 2 3import org.springframework.beans.factory.BeanFactory; 4import org.springframework.context.ApplicationContext; 5import org.springframework.context.support.ClassPathXmlApplicationContext; 6 7import Services.IAOPServices; 8 9public class App { 10 11 public static void main(String[] args) throws Exception { 12 13 ApplicationContext context=new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}); 14 BeanFactory factory=context; 15 IAOPServices services=(IAOPServices)context.getBean("serviceImplA"); 16 services.withAopMethod(); 17 services.withNoAopMethod(); 18 } 19}
View Code
运行结果如下:

三、AspectJ基于注解的配置
AspectJ基于XML的配置还是需要在XML中配置AOP元素,现在一般提倡使用注解来进行编程,AspectJ也提供了基于注解的实现方式。基于注解的AOP配置其实和基于XML的一样,可以参照基于XML的来进行理解。这里定义了AnnontationAdvice,并用@Aspect注解定义切面。在XML中的配置元素改成了注解关键字。

1package Services; 2 3import org.aspectj.lang.JoinPoint; 4import org.aspectj.lang.ProceedingJoinPoint; 5import org.aspectj.lang.annotation.After; 6import org.aspectj.lang.annotation.AfterReturning; 7import org.aspectj.lang.annotation.AfterThrowing; 8import org.aspectj.lang.annotation.Around; 9import org.aspectj.lang.annotation.Aspect; 10import org.aspectj.lang.annotation.Before; 11import org.springframework.stereotype.Component; 12 13@Component 14@Aspect 15public class AnnontationAdvice { 16 17 @Before("execution(* Services.*.withAop*(..))") 18 public void beforeAdvice() { 19 System.out.println("前置通知执行了"); 20 } 21 22 @After("execution(* Services.*.withAop*(..))") 23 public void afterAdvice() { 24 System.out.println("后置通知执行了"); 25 } 26 27 @AfterReturning(value="execution(* Services.*.withAop*(..))",returning="result") 28 public void afterReturnAdvice(String result) { 29 System.out.println("返回通知执行了" + "运行业务方法返回的结果为" + result); 30 } 31 32 @Around(value="execution(* Services.*.withAop*(..))") 33 public String aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { 34 String result = ""; 35 try { 36 System.out.println("环绕通知开始执行了"); 37 long start = System.currentTimeMillis(); 38 result = (String) proceedingJoinPoint.proceed(); 39 long end = System.currentTimeMillis(); 40 System.out.println("环绕通知执行结束了"); 41 System.out.println("执行业务方法共计:" + (end - start) + "毫秒。"); 42 } catch (Throwable e) { 43 44 } 45 return result; 46 } 47 @AfterThrowing(value="execution(* Services.*.withAop*(..))",throwing="e") 48 public void throwingAdvice(JoinPoint joinPoint, Exception e) { 49 StringBuffer stringBuffer = new StringBuffer(); 50 stringBuffer.append("异常通知执行了."); 51 stringBuffer.append("方法:").append(joinPoint.getSignature().getName()).append("出现了异常."); 52 stringBuffer.append("异常信息为:").append(e.getMessage()); 53 System.out.println(stringBuffer.toString()); 54 } 55}
View Code
在配置文件中只需配置下自动扫描的包名,并配置下aop:aspectj-autoproxy即可,比XML的配置简单一些。

1<?xml version="1.0" encoding="UTF-8"?> 2<beans xmlns="http://www.springframework.org/schema/beans" 3xmlns:context="http://www.springframework.org/schema/context" 4xmlns:mvc="http://www.springframework.org/schema/mvc" 5xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 6xmlns:aop="http://www.springframework.org/schema/aop" 7xsi:schemaLocation=" 8http://www.springframework.org/schema/beans 9http://www.springframework.org/schema/beans/spring-beans.xsd 10http://www.springframework.org/schema/context 11http://www.springframework.org/schema/context/spring-context.xsd 12http://www.springframework.org/schema/mvc 13http://www.springframework.org/schema/mvc/spring-mvc.xsd 14http://www.springframework.org/schema/aop 15http://www.springframework.org/schema/aop/spring-aop.xsd 16"> 17 <!-- 配置自动扫描的包 --> 18 <context:component-scan base-package="Services"></context:component-scan> 19 <!-- 自动为切面方法中匹配的方法所在的类生成代理对象。 --> 20 <aop:aspectj-autoproxy></aop:aspectj-autoproxy> 21</beans> 22<bean id="serviceImplA" class="Services.AOPServicesImpl"> 23 <property name="description" value="basicAop"></property> 24</bean>
View Code
最后还是从Spring容器中获取IAOPServices对象,并分别执行IAOPServices中的两个方法。运行结果如下图,从打印的日志可以看到拦截器拦截了withAopMethod()方法,withNoAopMethod()并未拦截。
运行结果如下:
