springAOP

(一)AOP前奏

WHY AOP ?

在这里插入图片描述

需求1-日志:在程序执行期间追踪正在发生的活动
需求2-验证:希望计算器只能处理正数的运算

在这里插入图片描述

代码混乱:越来越多的非业务需求(日志和验证等)加入后, 原有的业务方法急剧膨胀. 每个方法在处理核心逻辑的同时还必须兼顾其他多个关注点.
代码分散: 以日志需求为例, 只是为了满足这个单一需求, 就不得不在多个模块(方法)里多次重复相同的日志代码. 如果日志需求发生变化, 必须修改所有模块.

使用动态代理解决上述问题:
代理设计模式的原理: 使用一个代理将对象包装起来, 然后用该代理对象取代原始对象. 任何对原始对象的调用都要通过代理. 代理对象决定是否以及何时将方法调用转到原始对象上.

被代理对象的类:

public class ArithmeticCalculatorImpl implements ArithmeticCalculator {

	@Override
	public int add(int i, int j) {
		int result = i + j;
		return result;
	}

	@Override
	public int sub(int i, int j) {
		int result = i - j;
		return result;
	}

	@Override
	public int mul(int i, int j) {
		int result = i * j;
		return result;
	}

	@Override
	public int div(int i, int j) {
		int result = i / j;
		return result;
	}

}

代理对象的类:

public class ArithmeticCalculatorLoggingProxy {
	
	//要代理的对象
	private ArithmeticCalculator target;
	
	public ArithmeticCalculatorLoggingProxy(ArithmeticCalculator target) {
		super();
		this.target = target;
	}

	//返回代理对象
	public ArithmeticCalculator getLoggingProxy(){
		ArithmeticCalculator proxy = null;
		//代理对象由哪一个类加载器加载
		ClassLoader loader = target.getClass().getClassLoader();
		//代理对象的类型,即其中有哪些方法
		Class [] interfaces = new Class[]{ArithmeticCalculator.class};
		//当调用代理对象其中的方法时,该执行的代码
		InvocationHandler h = new InvocationHandler() {
			/**
			 * proxy: 代理对象。 一般不使用该对象
			 * method: 正在被调用的方法
			 * args: 调用方法传入的参数
			 */
			@Override
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				String methodName = method.getName();
				//打印日志
				System.out.println("[before] The method " + methodName + " begins with " + Arrays.asList(args));
				
				//调用目标方法
				Object result = null;
				
				try {
					//前置通知
					result = method.invoke(target, args);
					//返回通知, 可以访问到方法的返回值
				} catch (NullPointerException e) {
					e.printStackTrace();
					//异常通知, 可以访问到方法出现的异常
				}
				
				//后置通知. 因为方法可以能会出异常, 所以访问不到方法的返回值
				
				//打印日志
				System.out.println("[after] The method ends with " + result);
				
				return result;
			}
		};
		
		/**
		 * loader: 代理对象使用的类加载器。 
		 * interfaces: 指定代理对象的类型. 即代理代理对象中可以有哪些方法. 
		 * h: 当具体调用代理对象的方法时, 应该如何进行响应, 实际上就是调用 InvocationHandler 的 invoke 方法
		 */
		proxy = (ArithmeticCalculator) Proxy.newProxyInstance(loader, interfaces, h);
		
		return proxy;
	}
}

运行Main:

public static void main(String[] args) {
		ArithmeticCalculator arithmeticCalculator = new ArithmeticCalculatorImpl();
		
		arithmeticCalculator = 
				new ArithmeticCalculatorLoggingProxy(arithmeticCalculator).getLoggingProxy();
		
		int result = arithmeticCalculator.add(11, 12);
		System.out.println("result:" + result);
		
		result = arithmeticCalculator.div(21, 3);
		System.out.println("result:" + result);
		
	}
	
}

运行结果:

[before] The method add begins with [11, 12]
[after] The method ends with 23
result:23

代理对象就是本身不是包含实际功能的对象,它就是一个传声筒,它调用被代理的对象,并且把返回结果再传给调用代理对象的对象。被代理对象就是实际拥有功能调用的对象。

(二)AOP简介

AOP(Aspect-Oriented Programming, 面向切面编程): 是一种新的方法论, 是对传统 OOP(Object-Oriented Programming, 面向对象编程) 的补充.
AOP 的主要编程对象是切面(aspect), 而切面模块化横切关注点.
在应用 AOP 编程时, 仍然需要定义公共功能, 但可以明确的定义这个功能在哪里, 以什么方式应用, 并且不必修改受影响的类. 这样一来横切关注点就被模块化到特殊的对象(切面)里.
AOP 的好处:
每个事物逻辑位于一个位置, 代码不分散, 便于维护和升级
业务模块更简洁, 只包含核心业务代码.

在这里插入图片描述

(三)AOP术语

切面(Aspect): 横切关注点(跨越应用程序多个模块的功能)被模块化的特殊对象

在这里插入图片描述

通知(Advice): 切面必须要完成的工作

是标注有某种注解的简单的 Java 方法.@Before或者@After

目标(Target): 被通知的对象

在这里插入图片描述

代理(Proxy): 向目标对象应用通知之后创建的对象
在这里插入图片描述

连接点(Joinpoint):程序执行的某个特定位置:如类某个方法调用前、调用后、方法抛出异常后等。连接点由两个信息确定:方法表示的程序执行点;相对点表示的方位。例如 ArithmethicCalculator#add() 方法执行前的连接点,执行点为 ArithmethicCalculator#add(); 方位为该方法执行前的位置
切点(pointcut):每个类都拥有多个连接点:例如 ArithmethicCalculator 的所有方法实际上都是连接点,即连接点是程序类中客观存在的事务。AOP 通过切点定位到特定的连接点。类比:连接点相当于数据库中的记录,切点相当于查询条件。切点和连接点不是一对一的关系,一个切点匹配多个连接点,切点通过 org.springframework.aop.Pointcut 接口进行描述,它使用类和方法作为连接点的查询条件。

(四)在 Spring 中启用 AspectJ 注解支持

AspectJ:Java 社区里最完整最流行的 AOP 框架.
在 Spring2.0 以上版本中, 可以使用基于 AspectJ 注解或基于 XML 配置的 AOP

要在 Spring 应用中使用 AspectJ 注解, 必须在 classpath 下包含 AspectJ 类库: aopalliance.jar、aspectj.weaver.jar 和 spring-aspects.jar

在这里插入图片描述

将 aop Schema 添加到 根元素中.

xmlns:aop="http://www.springframework.org/schema/aop"

要在 Spring IOC 容器中启用 AspectJ 注解支持, 只要在 Bean 配置文件中定义一个空的 XML 元素 aop:aspectj-autoproxy

<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.atguigu.spring.aop"></context:component-scan>

<!-- 配置自动为匹配 aspectJ 注解的 Java 类生成代理对象 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

当 Spring IOC 容器侦测到 Bean 配置文件中的 aop:aspectj-autoproxy 元素时, 会自动为与 AspectJ 切面匹配的 Bean 创建代理.

用 AspectJ 注解声明切面:

要在 Spring 中声明 AspectJ 切面, 只需要在 IOC 容器中将切面声明为 Bean 实例.

@Aspect//声明切面
@Component//在 IOC 容器中将切面声明为 Bean 实例
public class LoggingAspect {}

当在 Spring IOC 容器中初始化 AspectJ 切面之后, Spring IOC 容器就会为那些与 AspectJ 切面相匹配的 Bean 创建代理.
在 AspectJ 注解中, 切面只是一个带有 @Aspect 注解的 Java 类.

@Component//在 IOC 容器中将切面声明为 Bean 实例
public class LoggingAspect {}

通知是标注有某种注解的简单的 Java 方法.
AspectJ 支持 5 种类型的通知注解:
@Before: 前置通知, 在方法执行之前执行

declareJointPointExpression()重用切入点定义有介绍!!!

/**
* 在 com.atguigu.spring.aop.ArithmeticCalculator 接口的每一个实现类的每一个方法开始之前执行一段代码
 */
@Before("declareJointPointExpression()")//使用方法名来引用当前的切入点表达式. 
public void beforeMethod(JoinPoint joinPoint){
	String methodName = joinPoint.getSignature().getName();
	Object [] args = joinPoint.getArgs();
	
	System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));
}

@After: 后置通知, 在方法执行之后执行

/**
 * 在方法执行之后执行的代码. 无论该方法是否出现异常
 */
@After("declareJointPointExpression()")
public void afterMethod(JoinPoint joinPoint){
	String methodName = joinPoint.getSignature().getName();
	System.out.println("The method " + methodName + " ends");
}

@AfterRunning: 返回通知, 在方法返回结果之后执行

/**
* 在方法法正常结束受执行的代码
* 返回通知是可以访问到方法的返回值的!
*/
@AfterReturning(value="declareJointPointExpression()",
	returning="result")
public void afterReturning(JoinPoint joinPoint, Object result){
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " ends with " + result);
}

@AfterThrowing: 异常通知, 在方法抛出异常之后

/**
* 在目标方法出现异常时会执行的代码.
 * 可以访问到异常对象; 且可以指定在出现特定异常时在执行通知代码
 */
@AfterThrowing(value="declareJointPointExpression()",
		throwing="e")
public void afterThrowing(JoinPoint joinPoint, Exception e){
	String methodName = joinPoint.getSignature().getName();
	System.out.println("The method " + methodName + " occurs excetion:" + e);
}

@Around: 环绕通知, 围绕着方法执行

/**
* 环绕通知需要携带 ProceedingJoinPoint 类型的参数. 
 * 环绕通知类似于动态代理的全过程: ProceedingJoinPoint 类型的参数可以决定是否执行目标方法.
 * 且环绕通知必须有返回值, 返回值即为目标方法的返回值
 */

@Around("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.*(..))")
public Object aroundMethod(ProceedingJoinPoint pjd){
	
	Object result = null;
	String methodName = pjd.getSignature().getName();
	
	try {
		//前置通知
		System.out.println("The method " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));
		//执行目标方法
		result = pjd.proceed();
		//返回通知
		System.out.println("The method " + methodName + " ends with " + result);
	} catch (Throwable e) {
		//异常通知
		System.out.println("The method " + methodName + " occurs exception:" + e);
		throw new RuntimeException(e);
	}
	//后置通知
	System.out.println("The method " + methodName + " ends");
	
	return result;
}

(五)指定切面的优先级

在同一个连接点上应用不止一个切面时, 除非明确指定, 否则它们的优先级是不确定的.
切面的优先级可以通过实现 Ordered 接口或利用 @Order 注解指定.
实现 Ordered 接口, getOrder() 方法的返回值越小, 优先级越高.
若使用 @Order 注解, 序号出现在注解中
在这里插入图片描述
在这里插入图片描述

(六)重用切入点定义

在编写 AspectJ 切面时, 可以直接在通知注解中书写切入点表达式. 但同一个切点表达式可能会在多个通知中重复出现.
在 AspectJ 切面中, 可以通过 @Pointcut 注解将一个切入点声明成简单的方法. 切入点的方法体通常是空的, 因为将切入点定义与应用程序逻辑混在一起是不合理的.
切入点方法的访问控制符同时也控制着这个切入点的可见性. 如果切入点要在多个切面中共用, 最好将它们集中在一个公共的类中. 在这种情况下, 它们必须被声明为 public. 在引入这个切入点时, 必须将类名也包括在内. 如果类没有与这个切面放在同一个包中, 还必须包含包名.
其他通知可以通过方法名称引入该切入点.

/**
* 定义一个方法, 用于声明切入点表达式. 一般地, 该方法中再不需要添入其他的代码. 
 * 使用 @Pointcut 来声明切入点表达式. 
 * 后面的其他通知直接使用方法名来引用当前的切入点表达式. 
 */
@Pointcut("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.*(..))")
public void declareJointPointExpression(){}

!!!如果不懂看第第四小节 — 在 Spring 中启用 AspectJ 注解支持

(七)引入通知(很少使用,可以不看)

引入通知是一种特殊的通知类型. 它通过为接口提供实现类, 允许对象动态地实现接口, 就像对象已经在运行时扩展了实现类一样.
在这里插入图片描述

引入通知可以使用两个实现类 MaxCalculatorImpl 和 MinCalculatorImpl, 让 ArithmeticCalculatorImpl 动态地实现 MaxCalculator 和 MinCalculator 接口. 而这与从 MaxCalculatorImpl 和 MinCalculatorImpl 中实现多继承的效果相同. 但却不需要修改 ArithmeticCalculatorImpl 的源代码
引入通知也必须在切面中声明
在切面中, 通过为任意字段添加@DeclareParents 注解来引入声明.
注解类型的 value 属性表示哪些类是当前引入通知的目标. value 属性值也可以是一个 AspectJ 类型的表达式, 以将一个即可引入到多个类中. defaultImpl 属性中指定这个接口使用的实现类

在这里插入图片描述

在这里插入图片描述

(八)用基于 XML 的配置声明切面

除了使用 AspectJ 注解声明切面, Spring 也支持在 Bean 配置文件中声明切面. 这种声明是通过 aop schema 中的 XML 元素完成的.
正常情况下, 基于注解的声明要优先于基于 XML 的声明. 通过 AspectJ 注解, 切面可以与 AspectJ 兼容, 而基于 XML 的配置则是 Spring 专有的. 由于 AspectJ 得到越来越多的 AOP 框架支持, 所以以注解风格编写的切面将会有更多重用的机会.

基于 XML ---- 声明切面:
当使用 XML 声明切面时, 需要在 根元素中导入 aop Schema

xmlns:aop="http://www.springframework.org/schema/aop"

在 Bean 配置文件中, 所有的 Spring AOP 配置都必须定义在 aop:config 元素内部. 对于每个切面而言, 都要创建一个 aop:aspect 元素来为具体的切面实现引用后端 Bean 实例.
切面 Bean 必须有一个标示符, 供 aop:aspect 元素引用

<!-- 配置 bean -->
<bean id="arithmeticCalculator" 
	class="com.atguigu.spring.aop.xml.ArithmeticCalculatorImpl"></bean>

<!-- 配置切面的 bean. -->
<bean id="loggingAspect"
	class="com.atguigu.spring.aop.xml.LoggingAspect"></bean>

<bean id="vlidationAspect"
	class="com.atguigu.spring.aop.xml.VlidationAspect"></bean>

<!-- 配置 AOP -->
<aop:config>
		
	<!-- 配置切面及通知 -->
	<aop:aspect ref="loggingAspect" order="2">		
	</aop:aspect>
	
	<aop:aspect ref="vlidationAspect" order="1">
	</aop:aspect>
	
</aop:config>

基于 XML ---- 声明切入点:
切入点使用 aop:pointcut 元素声明
切入点必须定义在 aop:aspect 元素下, 或者直接定义在 aop:config 元素下.
定义在 aop:aspect 元素下: 只对当前切面有效
定义在 aop:config 元素下: 对所有切面都有效
基于 XML 的 AOP 配置不允许在切入点表达式中用名称引用其他切入点.

<!-- 配置 AOP -->
<aop:config>
	
	<!-- 配置切点表达式 -->
		<aop:pointcut expression="execution(* com.atguigu.spring.aop.xml.ArithmeticCalculator.*(int, int))" 
			id="pointcut"/>
		
	<!-- 配置切面及通知 -->
	<aop:aspect ref="loggingAspect" order="2">		
	</aop:aspect>
	
	<aop:aspect ref="vlidationAspect" order="1">
	</aop:aspect>
	
</aop:config>

基于 XML ---- 声明通知:
在 aop Schema 中, 每种通知类型都对应一个特定的 XML 元素.
通知元素需要使用 来引用切入点, 或用 直接嵌入切入点表达式. method 属性指定切面类中通知方法的名称.

<!-- 配置 AOP -->
<aop:config>
	
	<!-- 配置切点表达式 -->
		<aop:pointcut expression="execution(* com.atguigu.spring.aop.xml.ArithmeticCalculator.*(int, int))" 
			id="pointcut"/>
		
	<!-- 配置切面及通知 -->
	<aop:aspect ref="loggingAspect" order="2">
		<aop:before method="beforeMethod" pointcut-ref="pointcut"/>
		<aop:after method="afterMethod" pointcut-ref="pointcut"/>
		<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e"/>
		<aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/>
		<!--  
		<aop:around method="aroundMethod" pointcut-ref="pointcut"/>
		-->		
	</aop:aspect>
	
	<aop:aspect ref="vlidationAspect" order="1">
		<aop:before method="validateArgs" pointcut-ref="pointcut"/>
	</aop:aspect>
	
</aop:config>

声明引入:
可以利用 aop:declare-parents 元素在切面内部声明引入
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值