文章目录
一, 动态代理
1. 模式的引出
- 代码混乱:越来越多的非业务需求(日志和验证等)加入后, 原有的业务方法急剧膨胀. 每个方法在处理核心逻辑的同时还必须兼顾其他多个关注点.
- 代码分散: 以日志需求为例, 只是为了满足这个单一需求, 就不得不在多个模块(方法)里多次重复相同的日志代码. 如果日志需求发生变化, 必须修改所有模块.
//接口
public interface ArithmeticCalculator {
public int add(int i,int j);
public int sub(int i,int j);
public int mul(int i,int j);
public int div(int i,int j);
}
public class ArithmeticCalculatorLoggingImpl implements ArithmeticCalculator {
//添加日志 重复的代码繁多 高耦合 不好
public int add(int i, int j) {
System.out.println("the method add begin with ["+i+","+j+"]");
int result=i+j;
System.out.println("the method add ends with"+result);
return result;
}
public int sub(int i, int j) {
System.out.println("the method sub begin with ["+i+","+j+"]");
int result=i-j;
System.out.println("the method sub ends with"+result);
return result;
}
public int mul(int i, int j) {
System.out.println("the method mul begin with ["+i+","+j+"]");
int result=i*j;
System.out.println("the method mul ends with"+result);
return result;
}
public int div(int i, int j) {
System.out.println("the method div begin with ["+i+","+j+"]");
int result=i/j;
System.out.println("the method div ends with"+result);
return result;
}
}
2.模式的原理
-
使用一个代理将对象包装起来, 然后用该代理对象取代原始对象. 任何对原始对象的调用都要通过代理. 代理对象决定是否以及何时将方法调用转到原始对象上.
-
代码如下
//测试类
ArithmeticCalculator arithmeticCalculator = new ArithmeticCalculatorImpl();
arithmeticCalculator =
new ArithmeticCalcualtorLoggingProxy(arithmeticCalculator).getLoggingProxy();
int result = arithmeticCalculator.add(11, 12);
System.out.println("result:" + result);
result = arithmeticCalculator.div(21, 3);
System.out.println("result:" + result);
//动态代理类
public class ArithmeticCalcualtorLoggingProxy {
//动态代理
//要代理的对象
private ArithmeticCalculator target;
public ArithmeticCalcualtorLoggingProxy(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: 调用方法传入的参数
*/
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;
}
}
- 上述动态代理依然比较麻烦,若使用SpringAOP则更加方便。
二,面向切面AOP
1.AOP 的概念和细节
-
面向切面编程,是对传统OOP面向对象编程的补充。主要编程对象是切面。
-
AOP编程时,仍然需要定义公共功能。并且不必修改受影响的类。这样依赖横切关注点就被模块化到特殊的对象(切面)里。
-
每个逻辑事物处于一个位置,代码不分散,便于维护和升级。业务模块更简洁。只包含核心业务代码。
-
基础语言
- 切面(Aspect):横切关注点被模块化的特殊对象 。
- 通知(Adive):切面必须要完成的工作。
- 目标(Target):被通知的对象。
- 代理(Proxy):向目标对象应用 通知之后创建的对象。
- 连接点(Joinpoint):程序执行的某个特定的位置。
- 切点(pointcut):AOP通过切点定位到特定的连接点。类比:连接点相当于数据库的记录,切点相当于查询条件。
-
AspectJ:AOP框架。使用基于AspectJ注解或基于XML配置的Aop.
//applicationContext-aop.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 自动扫描的包 -->
<context:component-scan base-package="com.xiaojian.spring.AOP"></context:component-scan>
<!-- 使 AspectJ 的注解起作用 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
- 注解声明切面
- AspectJ 支持 5 种类型的通知注解:
@Before: 前置通知, 在方法执行之前执行
@After: 后置通知, 在方法执行之后执行
@AfterReturnning: 返回通知, 在方法返回结果之后执行
@AfterThrowing: 异常通知, 在方法抛出异常之后
@Around: 环绕通知, 围绕着方法执行
- AspectJ 支持 5 种类型的通知注解:
2. 切面的编写过程(基于aspectJ注解)
1.前置通知与后置通知
package com.xiaojian.spring.AOP;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/**
* AOP 面向切面编程
* 1.加入jar包
* 2.在spring的配置文件中加入aop的命名空间
* 3.基于注解的方式来使用aop
* 3.1 在配置文件中配置自动扫描的包
* 3.2 加入使AspjectJ注解起作用的配置
*
* 4.编写切面类:
* 4.1 一个一般的Java类
* 4.2 在其中添加要额外实现的类
*
* 5.配置切面
* 5.1 切面必须是IOC容器中的bean。添加注解@Component注解
* 5.2 声明式一个切面:@Aspect
* 5.3 声明通知,即添加额外的功能对应的方法
* @before前置通知
* @after 后置通知
* @author lovexx
*
*/
@Aspect
@Component
public class LoggingAspect {
//参数的问题
@Before("execution(public int com.xiaojian.spring.AOP.*.*(..))")
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("execution(public int com.xiaojian.spring.AOP.*.*(..))")
public void afterMethod(JoinPoint joinPoint){
String mathodName = joinPoint.getSignature().getName();
System.out.println("the method"+mathodName+" ends ");
}
}
- 测试类
package com.xiaojian.spring.AOP;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-aop.xml");
ArithmeticCalculator arithmeticCalculator=(ArithmeticCalculator)ctx.getBean("arithmeticCalculator");
System.out.println(arithmeticCalculator.getClass().getName());
int result = arithmeticCalculator.add(10, 2);
System.out.println(result);
}
}
2. 返回通知,异常通知和环绕通知
- 返回通知 无论连接点是正常返回还是抛出异常, 后置通知都会执行. 如果只想在连接点返回的时候记录日志, 应使用返回通知代替后置通知。并且有返回值。
/**
* 在方法正常执行结束之后执行的一段代码
* 返回通知可以访问到该方法的返回值
*/
@AfterReturning(value="declareJointPointExpression()",returning="result")
public void afterReturnning(JoinPoint joinPoint,Object result){
String methodName = joinPoint.getSignature().getName();
System.out.println("the method"+methodName+"ends with"+result);
}
- 异常通知 只有连接点抛出异常才会有异常通知
/**
* 异常通知
* 在目标方法出现异常时会执行的代码
* 可以访问到异常对象,且可以指定在出现特定异常时再执行通知代码
*/
@AfterThrowing(value="declareJointPointExpression()",throwing="e")
public void afterThrowing(JoinPoint joinPoint,Exception e){
String methodName = joinPoint.getSignature().getName();
System.out.println("the method"+methodName+" occurs exception:"+e);
}
- 环绕通知
- 环绕通知是所有通知类型中功能最为强大的, 能够全面地控制连接点. 甚至可以控制是否执行连接点.
对于环绕通知来说, 连接点的参数类型必须是 ProceedingJoinPoint . 它是 JoinPoint 的子接口, 允许控制何时执行, 是否执行连接点. - 在环绕通知中需要明确调用 ProceedingJoinPoint 的 proceed() 方法来执行被代理的方法. 如果忘记这样做就会导致通知被执行了, 但目标方法没有被执行.
- 注意: 环绕通知的方法需要返回目标方法执行之后的结果, 即调用 joinPoint.proceed(); 的返回值, 否则会出现空指针异常
- 环绕通知是所有通知类型中功能最为强大的, 能够全面地控制连接点. 甚至可以控制是否执行连接点.
@Around("execution(public int com.xiaojian.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;
}
3. 引入通知(了解即可,无需代码说明)
3.指定切面的优先级
- 在同一个连接点上应用不止一个切面时, 除非明确指定, 否则它们的优先级是不确定的.
切面的优先级可以通过实现 Ordered 接口或利用 @Order 注解指定. - 实现 Ordered 接口, getOrder() 方法的返回值越小, 优先级越高.
- 若使用 @Order 注解, 序号出现在注解中
4. 重用切入点
- 在 AspectJ 切面中, 可以通过 @Pointcut 注解将一个切入点声明成简单的方法. 切入点的方法体通常是空的, 因为将切入点定义与应用程序逻辑混在一起是不合理的.
- 切入点方法的访问控制符同时也控制着这个切入点的可见性.
/**
* 定义一个方法, 用于声明切入点表达式. 一般地, 该方法中再不需要添入其他的代码.
* 使用 @Pointcut 来声明切入点表达式.
* 后面的其他通知直接使用方法名来引用当前的切入点表达式.
*/
@Pointcut("execution(public int com.xiaojian.spring.aop.*.*(..))")
public void declareJointPointExpression(){}
5.基于XML的配置AOP
- 配置文件
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<!-- 配置 bean -->
<bean id="arithmeticCalculator"
class="com.xiaojian.spring.aop.xml.ArithmeticCalculatorImpl"></bean>
<!-- 配置切面的 bean. -->
<bean id="loggingAspect"
class="com.xiaojian.spring.aop.xml.LoggingAspect"></bean>
<!-- 配置 AOP -->
<aop:config>
<!-- 配置切点表达式 -->
<aop:pointcut expression="execution(* com.xiaojian.spring.aop.xml.ArithmeticCalculator.*(..))"
id="pointcut"/>
<!-- 配置切面及通知 -->
<aop:aspect ref="loggingAspect" >
<aop:before method="beforeMethod" pointcut-ref="pointcut"/>
<aop:after method="afterMethod" pointcut-ref="pointcut"/>
<aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/>
<!--
<aop:around method="aroundMethod" pointcut-ref="pointcut"/>
-->
</aop:aspect>
</aop:config>
</beans>
- 接口类
package com.xiaojian.spring.aop.xml;
public interface ArithmeticCalculator {
public int add(int i,int j);
public int sub(int i,int j);
public int mul(int i,int j);
public int div(int i,int j);
}
- 接口的实现类
package com.xiaojian.spring.aop.xml;
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
public int add(int i, int j) {
int result = i+j;
return result;
}
public int sub(int i, int j) {
int result = i-j;
return result;
}
public int mul(int i, int j) {
int result = i*j;
return result;
}
public int div(int i, int j) {
int result = i/j;
return result;
}
}
- 测试类
package com.xiaojian.spring.aop.xml;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-xml.xml");
ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator");
System.out.println(arithmeticCalculator.getClass().getName());
int result = arithmeticCalculator.add(1, 2);
System.out.println("result:" + result);
}
}
- 切面类
package com.xiaojian.spring.aop.xml;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
public class LoggingAspect {
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));
}
public void afterMethod(JoinPoint joinPoint){
String mathodName = joinPoint.getSignature().getName();
System.out.println("the method"+mathodName+" ends ");
}
public void afterReturnning(JoinPoint joinPoint,Object result){
String methodName = joinPoint.getSignature().getName();
System.out.println("the method"+methodName+"ends with"+result);
}
}