AOP(Aspect oriented programming)面向切面编程

 AOP(Aspect oriented programming)面向切面编程

AOP(Aspect oriented programming)面向切面编程

希望达到核心业务与系统服务之间相对独立,而又想让核心业务带着系统层面的功能,实现这种效果的技术我们称之为AOP.

AOP采用的是横向抽取机制,将分散在个方法的重复代码抽取出来,然后在程序的编译期或者运行期在将这些代码运行到需要执行的地方。

本质:通过代理的方式进行方法的增强。

aop实现管理:

  • JDK动态代理:基于接口的,只能代理接口
  • CGLIB代理:通过字节码进行的

Aop核心:

  1. 通知(Advice):在哪个时间点去做增强,方法执行前?执行后?返回后?异常后?

通知的用法:https://blog.****.net/NaXieNianWoMenYiQ/article/details/88560990

     通知类型:

  • 前通知:方法执行前
  • 后通知:方法执行后
  • 返回后通知:成功返回后
  • 环绕通知:方法执行的前后分别做一些增强
  • 异常通知:抛出异常后
  1. 切点(PointCut):对那些类、哪些方法进行增强
  • 基于正则表达式的切点 JDKR**PointCut
  • 基于AOP的切点表达式AspectJ AsperctEx**PointCut

AOP=通知+切点

xml编写

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	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">
	<!-- 带被功能增强的类 -->
	<bean id="person" class="com.cbb.bean.Person"></bean>
	
	<!-- 配置一个切面 -->
	<bean id="myAdvice" class="com.cbb.advice.MyAdivice"></bean>
	
	<!-- aop配置 -->
	<aop:config>
	<!-- aop配置切面  通过ref指向增强的bean切面-->
		<aop:aspect ref="myAdvice">
		<!-- aop配置切点  可以放到切面里面可以使用这个切点,也可以放在切面外部,代表全局的,所有的切面都可以使用这个切点
		expression:写切点表达式-->
			<aop:pointcut expression="execution(* com.cbb.bean.*.*(..))" id="myCut"/>
			<!-- 配置前通知 method:对应切面的哪个方法 -->
			<aop:before method="doBefore" pointcut-ref="myCut"/>
		</aop:aspect>
	</aop:config>
</beans>

关于切点配置的expression属性:

AOP(Aspect oriented programming)面向切面编程

功能:

1. 可以控制返回值
2. 可以控制参数

3. 可以控制类的 深度

4. : 面向接口的。 接口方法被切,则此接口的实现类方法也会被切。

* 在返回值上,代表的是任意类型。 在路径上,代表任意类或者是方法
.. 任意多个。0~N个