1.aop简介
AOP(Aspect-Oriented Programming, 面向切面编程): 是一种新的方法论, 是对传统 OOP(Object-Oriented Programming, 面向对象编程) 的补充.
AOP 的好处:
每个事务逻辑位于一个位置, 代码不分散, 便于维护和升级
业务模块更简洁, 只包含核心业务代码. 非侵入式编程
2. AOP 术语
切面(Aspect): 横切关注点(跨越应用程序多个模块的功能)被模块化的特殊对象
通知(Advice): 切面必须要完成的工作
前置通知:在方法之前执行
后置通知:在方法之后执行
异常通知:方法出现异常
终止通知:在后置之后执行
环绕通知:在方法之前和之后执行
目标(Target): 被通知的对象
代理(Proxy): 向目标对象应用通知之后创建的对象
连接点(Joinpoint):程序执行的某个特定位置:如类某个方法调用前、调用后、方法抛出异常后等。连接点由两个信息确定:方法表示的程序执行点;相对点表示的方位。
切点(pointcut):每个类都拥有多个连接点:例如 ArithmethicCalculator 的所有方法实际上都是连接点,即连接点是程序类中客观存在的事务。AOP 通过切点定位到特定的连接点。类比:连接点相当于数据库中的记录,切点相当于查询条件。切点和连接点不是一对一的关系,一个切点匹配多个连接点,切点通过 org.springframework.aop.Pointcut 接口进行描述,它使用类和方法作为连接点的查询条件。
3. aop的原理
aop底层使用动态代理实现
(1)第一种情况,有接口情况,使用动态代理创建接口实现类代理对象
(2)第二种情况,没有接口情况,使用动态代理创建类的子类代理对象
aop底层使用动态代理实现 (1)第一种情况,有接口情况,使用动态代理创建接口实现类代理对象 (2)第二种情况,没有接口情况,使用动态代理创建类的子类代理对象 |
画图分析原理
----------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------
4.spring使用Aspectj
(1) 基于aspectj的xml配置
除导入基本jar包还需要导入aop
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.5.3</version>
</dependency>
(2)创建核心的spring配置文件 aop的约束
<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-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"
>
5. 使用表达式配置切入点
常用的表达式:
(1) execution(* cn.itcast.aop.book.add(..))
(2) Execution(* itcast.aop.book.*(..))
(3) Execution(* *.*(..))
匹配所有save开头的execution(* save*(..))
6.Aspectj的aop操作
<!-- 定义切点(搜索条件)
表达式 execution(返回值 包.类.方法(参数))
-->
<aop:config>
<!-- 配置切点-->
<aop:pointcut expression="execution(* cn.*..*.AfHouseOwner.seekMyHose(..))" id="myPointcut"/>
<!--配置切面
Method:增强的方法里面那个方法作为前置
pointcut-ref="myPointcut":哪个切入点
-->
<aop:aspect ref="message">
<aop:before method="beforeSeek" pointcut-ref="myPointcut"/>
<aop:after method="afterSeek" pointcut-ref="myPointcut"/>
<aop:after-throwing method="throwException" pointcut-ref="myPointcut"/>
</aop:aspect>
</aop:config>