如果说 IoC 是 Spring 的核心,那么面向切面编程就是 Spring 最为重要的功能之一了,在数据库事务中切面编程被广泛使用。
首先,在面向切面编程的思想里面,把功能分为核心业务功能,和周边功能。
所谓的周边功能:比如性能统计,日志,事务管理等等
周边功能在 Spring 的面向切面编程AOP思想里,即被定义为切面。
在面向切面编程AOP的思想里面,核心业务功能和切面功能分别独立进行开发,然后把切面功能和核心业务功能 "编织" 在一起,这就叫AOP。
AOP能够将那些与业务无关,却为业务模块所共同调用的逻辑或责任(例如事务处理、日志管理、权限控制等)封装起来,便于减少系统的重复代码,降低模块间的耦合度,并有利于未来的可拓展性和可维护性。
所谓通知指的就是指拦截到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类。
Spring中AOP代理由Spring的IOC容器负责生成、管理,其依赖关系也由IOC容器负责管理。因此,AOP代理可以直接使用容器中的其它bean实例作为目标,这种关系可由IOC容器的依赖注入提供。Spring创建代理的规则为:
当需要代理的类不是代理接口的时候,Spring会切换为使用CGLIB代理,也可强制使用CGLIB。
AOP编程其实是很简单的事情,步骤如下:
所以进行AOP编程的关键就是定义切入点和定义增强处理,一旦定义了合适的切入点和增强处理,AOP框架将自动生成AOP代理,即:代理对象的方法 = 增强处理+被代理对象的方法
<!-- aop --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.1</version> </dependency>
Spring 是方法级别的 AOP 框架,我们主要也是以某个类额某个方法作为连接点,另一种说法就是:选择哪一个类的哪一方法用以增强功能。
public class RentingService { public void service() { // 仅仅只是实现了核心的业务功能 System.out.println("签合同"); System.out.println("收房租"); } }
选择好了连接点就可以创建切面了,我们可以把切面理解为一个拦截器,当程序运行到连接点的时候,被拦截下来,在开头加入了初始化的方法,在结尾也加入了销毁的方法而已。
public class Broker { public void around(ProceedingJoinPoint joinPoint) { System.out.println("带租客看房"); System.out.println("谈价格"); try { joinPoint.proceed(); } catch (Throwable throwable) { throwable.printStackTrace(); } System.out.println("交钥匙"); } }
<!-- 装配 Bean--> <bean name="landlord" class="com.codedot.aop.RentingService"/> <bean id="broker" class="com.codedot.aop.Broker"/> <!-- 配置AOP --> <aop:config> <!-- where:在哪些地方(包.类.方法)做增加 --> <aop:pointcut id="landlordPoint" expression="execution(* com.codedot.aop.RentingService.service())"/> <!-- what:做什么增强 --> <aop:aspect id="logAspect" ref="broker"> <!-- when:在什么时机(方法前/后/前后) --> <aop:around pointcut-ref="landlordPoint" method="around"/> </aop:aspect> </aop:config>
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 |
定义切点 | —— |
public class SpringMainTest { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); RentingService rentingService = (RentingService) ac.getBean("landlord"); rentingService.service(); } }
输出:
带租客看房
谈价格
签合同
收房租
交钥匙
原文:https://www.cnblogs.com/myitnews/p/13286945.html