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 编程
- 在 Packge【service】下创建 【ProductService】类
-
package service; public class ProductService { public void doSomeService(){ System.out.println("doSomeService"); } }
- 在 xml 文件中装配该 bean:
<bean name="productService" class="service.ProductService" />
- 在【TestSpring】中编写测试代码,运行:
- 在 Packge【aspect】下准备日志切面 【LoggerAspect】类:
package aspect; import org.aspectj.lang.ProceedingJoinPoint; public class LoggerAspect { public Object log(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("start log:" + joinPoint.getSignature().getName()); Object object = joinPoint.proceed(); System.out.println("end log:" + joinPoint.getSignature().getName()); return object; } }
- 在 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" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean name="productService" class="service.ProductService" /> <bean id="loggerAspect" class="aspect.LoggerAspect"/> <!-- 配置AOP --> <aop:config> <!-- where:在哪些地方(包.类.方法)做增加 --> <aop:pointcut id="loggerCutpoint" expression="execution(* service.ProductService.*(..)) "/> <!-- what:做什么增强 --> <aop:aspect id="logAspect" ref="loggerAspect"> <!-- when:在什么时机(方法前/后/前后) --> <aop:around pointcut-ref="loggerCutpoint" method="log"/> </aop:aspect> </aop:config> </beans>
- 再次运行 TestSpring 中的测试代码,代码并没有改变,但是在业务方法运行之前和运行之后,都分别输出了日志信息: