Spring AOP 简介

如果说 IoC 是 Spring 的核心,那么面向切面编程就是 Spring 最为重要的功能之一了,在数据库事务中切面编程被广泛使用。

AOP 即 Aspect Oriented Program 面向切面编程

首先,在面向切面编程的思想里面,把功能分为核心业务功能,和周边功能。

  • 所谓的核心业务,比如登陆,增加数据,删除数据都叫核心业务
  • 所谓的周边功能,比如性能统计,日志,事务管理等等

周边功能在 Spring 的面向切面编程AOP思想里,即被定义为切面

在面向切面编程AOP的思想里面,核心业务功能和切面功能分别独立进行开发,然后把切面功能和核心业务功能 "编织" 在一起,这就叫AOP

AOP 的目的

AOP能够将那些与业务无关,却为业务模块所共同调用的逻辑或责任(例如事务处理、日志管理、权限控制等)封装起来,便于减少系统的重复代码降低模块间的耦合度,并有利于未来的可拓展性和可维护性

AOP 当中的概念:

  • 切入点(Pointcut)

    在哪些类,哪些方法上切入(where
  • 通知(Advice)

    在方法执行的什么实际(when:方法前/方法后/方法前后)做什么(what:增强的功能)
  • 切面(Aspect)

    切面 = 切入点 + 通知,通俗点就是:在什么时机,什么地方,做什么增强!
  • 织入(Weaving)

    把切面加入到对象,并创建出代理对象的过程。(由 Spring 来完成)

一个例子

为了更好的说明 AOP 的概念,我们来举一个实际中的例子来说明:

在上面的例子中,包租婆的核心业务就是签合同,收房租,那么这就够了,灰色框起来的部分都是重复且边缘的事,交给中介商就好了,这就是 AOP 的一个思想:让关注点代码与业务代码分离!

实际的代码

我们来实际的用代码感受一下

1.在 Package【pojo】下新建一个【Landlord】类(我百度翻译的包租婆的英文):

package pojo;

import org.springframework.stereotype.Component;

@Component("landlord")
public class Landlord { public void service() {
// 仅仅只是实现了核心的业务功能
System.out.println("签合同");
System.out.println("收房租");
}
}

2.在 Package【aspect】下新建一个中介商【Broker】类(我还是用的翻译...):

package aspect;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component; @Component
@Aspect
class Broker { @Before("execution(* pojo.Landlord.service())")
public void before(){
System.out.println("带租客看房");
System.out.println("谈价格");
} @After("execution(* pojo.Landlord.service())")
public void after(){
System.out.println("交钥匙");
}
}

3.在 applicationContext.xml 中配置自动注入,并告诉 Spring IoC 容器去哪里扫描这两个 Bean:

<?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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="aspect" />
<context:component-scan base-package="pojo" /> <aop:aspectj-autoproxy/>
</beans>

4.在 Package【test】下编写测试代码:

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.Landlord; public class TestSpring { public static void main(String[] args) { ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
Landlord landlord = (Landlord) context.getBean("landlord", Landlord.class);
landlord.service(); }
}

5.执行看到效果:

这个例子使用了一些注解,现在看不懂没有关系,但我们可以从上面可以看到,我们在 Landlord 的 service() 方法中仅仅实现了核心的业务代码,其余的关注点功能是根据我们设置的切面自动补全的。


使用注解来开发 Spring AOP

使用注解的方式已经逐渐成为了主流,所以我们利用上面的例子来说明如何用注解来开发 Spring AOP

第一步:选择连接点

Spring 是方法级别的 AOP 框架,我们主要也是以某个类额某个方法作为连接点,另一种说法就是:选择哪一个类的哪一方法用以增强功能。

    ....
public void service() {
// 仅仅只是实现了核心的业务功能
System.out.println("签合同");
System.out.println("收房租");
}
....

我们在这里就选择上述 Landlord 类中的 service() 方法作为连接点。

第二步:创建切面

选择好了连接点就可以创建切面了,我们可以把切面理解为一个拦截器,当程序运行到连接点的时候,被拦截下来,在开头加入了初始化的方法,在结尾也加入了销毁的方法而已,在 Spring 中只要使用 @Aspect 注解一个类,那么 Spring IoC 容器就会认为这是一个切面了:

package aspect;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component; @Component
@Aspect
class Broker { @Before("execution(* pojo.Landlord.service())")
public void before(){
System.out.println("带租客看房");
System.out.println("谈价格");
} @After("execution(* pojo.Landlord.service())")
public void after(){
System.out.println("交钥匙");
}
}
  • 注意: 被定义为切面的类仍然是一个 Bean ,需要 @Component 注解标注

代码部分中在方法上面的注解看名字也能猜出个大概,下面来列举一下 Spring 中的 AspectJ 注解:

注解 说明
@Before 前置通知,在连接点方法前调用
@Around 环绕通知,它将覆盖原有方法,但是允许你通过反射调用原有方法,后面会讲
@After 后置通知,在连接点方法后调用
@AfterReturning 返回通知,在连接点方法执行并正常返回后调用,要求连接点方法在执行过程中没有发生异常
@AfterThrowing 异常通知,当连接点方法异常时调用

有了上表,我们就知道 before() 方法是连接点方法调用前调用的方法,而 after() 方法则相反,这些注解中间使用了定义切点的正则式,也就是告诉 Spring AOP 需要拦截什么对象的什么方法,下面讲到。

第三步:定义切点

在上面的注解中定义了 execution 的正则表达式,Spring 通过这个正则表达式判断具体要拦截的是哪一个类的哪一个方法:

execution(* pojo.Landlord.service())

依次对这个表达式作出分析:

  • execution:代表执行方法的时候会触发
  • * :代表任意返回类型的方法
  • pojo.Landlord:代表类的全限定名
  • service():被拦截的方法名称

通过上面的表达式,Spring 就会知道应该拦截 pojo.Lnadlord 类下的 service() 方法。上面的演示类还好,如果多出都需要写这样的表达式难免会有些复杂,我们可以通过使用 @Pointcut 注解来定义一个切点来避免这样的麻烦:

package aspect;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component; @Component
@Aspect
class Broker { @Pointcut("execution(* pojo.Landlord.service())")
public void lService() {
} @Before("lService()")
public void before() {
System.out.println("带租客看房");
System.out.println("谈价格");
} @After("lService()")
public void after() {
System.out.println("交钥匙");
}
}

第四步:测试 AOP

编写测试代码,但是我这里因为 JDK 版本不兼容出现了 BUG....(尴尬...)

这就告诉我们:环境配置很重要...不然莫名其妙的 BUG 让你崩溃...

环绕通知

我们来探讨一下环绕通知,这是 Spring AOP 中最强大的通知,因为它集成了前置通知和后置通知,它保留了连接点原有的方法的功能,所以它及强大又灵活,让我们来看看:

package aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component; @Component
@Aspect
class Broker { // 注释掉之前的 @Before 和 @After 注解以及对应的方法
// @Before("execution(* pojo.Landlord.service())")
// public void before() {
// System.out.println("带租客看房");
// System.out.println("谈价格");
// }
//
// @After("execution(* pojo.Landlord.service())")
// public void after() {
// System.out.println("交钥匙");
// } // 使用 @Around 注解来同时完成前置和后置通知
@Around("execution(* pojo.Landlord.service())")
public void around(ProceedingJoinPoint joinPoint) {
System.out.println("带租客看房");
System.out.println("谈价格"); try {
joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
} System.out.println("交钥匙");
}
}

运行测试代码,结果仍然正确:


使用 XML 配置开发 Spring AOP

注解是很强大的东西,但基于 XML 的开发我们仍然需要了解,我们先来了解一下 AOP 中可以配置的元素:

AOP 配置元素 用途 备注
aop:advisor 定义 AOP 的通知其 一种很古老的方式,很少使用
aop:aspect 定义一个切面 ——
aop:before 定义前置通知 ——
aop:after 定义后置通知 ——
aop:around 定义环绕通知 ——
aop:after-returning 定义返回通知 ——
aop:after-throwing 定义异常通知 ——
aop:config 顶层的 AOP 配置元素 AOP 的配置是以它为开始的
aop:declare-parents 给通知引入新的额外接口,增强功能 ——
aop:pointcut 定义切点 ——

有了之前通过注解来编写的经验,并且有了上面的表,我们将上面的例子改写成 XML 配置很容易(去掉所有的注解):

<!-- 装配 Bean-->
<bean name="landlord" class="pojo.Landlord"/>
<bean id="broker" class="aspect.Broker"/> <!-- 配置AOP -->
<aop:config>
<!-- where:在哪些地方(包.类.方法)做增加 -->
<aop:pointcut id="landlordPoint"
expression="execution(* pojo.Landlord.service())"/>
<!-- what:做什么增强 -->
<aop:aspect id="logAspect" ref="broker">
<!-- when:在什么时机(方法前/后/前后) -->
<aop:around pointcut-ref="landlordPoint" method="around"/>
</aop:aspect>
</aop:config>

运行测试程序,看到正确结果:

扩展阅读:Spring【AOP模块】就这么简单关于 Spring AOP(AspectJ)你该知晓的一切(慎独读,有些深度...)

参考资料:

  • 《Java EE 互联网轻量级框架整合开发》
  • 《Java 实战(第四版)》
  • 万能的百度 and 万能的大脑

欢迎转载,转载请注明出处!

简书ID:@我没有三颗心脏

github:wmyskxz

欢迎关注公众微信号:wmyskxz_javaweb

分享自己的Java Web学习之路以及各种Java学习资料

Spring(4)——面向切面编程(AOP模块)的更多相关文章

  1. Spring学习手札(二)面向切面编程AOP

    AOP理解 Aspect Oriented Program面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术. 但是,这种说法有些片面,因为在软件工程中,AOP的价值体现的并 ...

  2. 04 Spring:01.Spring框架简介&&02.程序间耦合&&03.Spring的 IOC 和 DI&&08.面向切面编程 AOP&&10.Spring中事务控制

    spring共四天 第一天:spring框架的概述以及spring中基于XML的IOC配置 第二天:spring中基于注解的IOC和ioc的案例 第三天:spring中的aop和基于XML以及注解的A ...

  3. Spring IOP 面向切面编程

    Spring IOP  面向切面编程 AOP操作术语 Joinpoint(连接点):所谓连接点是指那些被拦截到的点.在spring中,这些点指的是方法,因为spring只支持方法类型的连接点.(类里面 ...

  4. Spring框架学习笔记(2)——面向切面编程AOP

    介绍 概念 面向切面编程AOP与面向对象编程OOP有所不同,AOP不是对OOP的替换,而是对OOP的一种补充,AOP增强了OOP. 假设我们有几个业务代码,都调用了某个方法,按照OOP的思想,我们就会 ...

  5. Spring之控制反转——IoC、面向切面编程——AOP

      控制反转——IoC 提出IoC的目的 为了解决对象之间的耦合度过高的问题,提出了IoC理论,用来实现对象之间的解耦. 什么是IoC IoC是Inversion of Control的缩写,译为控制 ...

  6. Spring框架系列(4) - 深入浅出Spring核心之面向切面编程(AOP)

    在Spring基础 - Spring简单例子引入Spring的核心中向你展示了AOP的基础含义,同时以此发散了一些AOP相关知识点; 本节将在此基础上进一步解读AOP的含义以及AOP的使用方式.@pd ...

  7. Spring学习笔记:面向切面编程AOP(Aspect Oriented Programming)

    一.面向切面编程AOP 目标:让我们可以“专心做事”,避免繁杂重复的功能编码 原理:将复杂的需求分解出不同方面,将公共功能集中解决 *****所谓面向切面编程,是一种通过预编译方式和运行期动态代理实现 ...

  8. 面向切面编程(Aop)

    AOP中的概念 AOP(Aspect Orient Programming),也就是面向切面编程.可以这样理解,面向对象编程(OOP)是从静态角度考虑程序结构,面向切面编程(AOP)是从动态角度考虑程 ...

  9. 利用例子来理解spring的面向切面编程

    最近学习了spring的面向切面编程,在网上看到猴子偷桃的例子,觉得这种方式学习比书本上讲解有趣多了,也便于理解.现在就来基于猴子偷桃写个基本的例子. maven工程:

随机推荐

  1. Object.defineProperty实现数据绑定

    1.Object.defineProperty方法 Object.defineProperty(obj, prop, descriptor); (1)参数:  obj:目标对象 prop:需要定义的属 ...

  2. 用java理解程序逻辑小结

    1.Java常见的注释有哪些,语法是怎样的? 1)单行注释用//表示,编译器看到//会忽略该行//后的所文本 2)多行注释/* */表示,编译器看到/*时会搜索接下来的*/,忽略掉/* */之间的文本 ...

  3. WCF配置问题(配置WCF跨域)

    其它的先放一边.今天先来分享一下前段时间给公司做网站WCF服务接口的心得. 配置文件的配置问题 这里既然讨论WCF配置文件的问题,那么怎么创建的就不一一讲解了.好多博主都有提过的.所以直接分享自己开发 ...

  4. GLES2学习VBO和VAO的使用

    在GLES2中使用VBO和VAO对象,已经简单vs,ps绘制一个三角形. 1. 初始化操作代码,创建VBO.VAO,编译和链接shader program. void DebugApplication ...

  5. apache学习教程

    5.apache教程 httpd.conf文件分析 ServerRoot "E:/phpwebenv/PHPTutorial/Apache" #apache软件安装的位置 List ...

  6. AWS中的Internet 网关

    nternet 网关是一种横向扩展.支持冗余且高度可用的 VPC 组件,可实现 VPC 中的实例与 Internet 之间的通信.因此它不会对网络流量造成可用性风险或带宽限制. Internet 网关 ...

  7. RAID 损坏后如何对物理硬盘做完整镜像

    "磁盘阵列是由很多价格较便宜的磁盘,组合成一个容量巨大的磁盘组,利用个别磁盘提供数据所产生加成效果提升整个磁盘系统效能.利用这项技术,将数据切割成许多区段,分别存放在各个硬盘上." ...

  8. JAVA类的方法调用和变量(全套)

    一.类的分类: 1.普通类 2.抽象类(含有抽象方法的类) 3.静态类(不需要实例化,就可以使用的类) 二.方法的分类: 1.私有方法(只有类的内部才可以访问的方法) 2.保护方法(只有类的内部和该该 ...

  9. Linux的安装和使用技巧

    LinuxCentOs开始设置一个普通的用户,如果想进入root用户,可以su然后设置密码,然后第二次再次输入su,然后输入相同的密码就可以进去了 有很多命令需要在root下才能执行,但是在创建时却是 ...

  10. mysql数据库基本操作

    下载地址 http://www.mysql.com/downloads/mysql/ 端口号:3306 用户名:root 密码:自定义 连接到MySQL服务器 >mysql -uroot -pr ...