Spring4.0学习11--AOP

动态代理

在业务处理时,有时候我们需要添加一些日志等非核心的需求代码,如果这些代码分散在各个核心代码间会很冗余,不利于管理和维护,这时候我们可以使用动态代理来解决以上问题。
举个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Override
public int add(int i, int j) {
// TODO Auto-generated method stub
System.out.println("The method begins with (i: " +i+ ", j: "+j+")");
int result = i + j;
System.out.println("ends with" + result);
return result;
}
@Override
public int sub(int i, int j) {
// TODO Auto-generated method stub
System.out.println("The method begins with (i: " +i+ ", j: "+j+")");
int result = i - j;
System.out.println("ends with" + result);
return result;
}

上述代码中,在add()和sub()方法里都有打印输出的代码,万一方法一多,每个方法里面都有这种打印输出的代码时就很难去维护了,这些代码虽然不是核心代码但是在开发过程中也是可以帮助我们定位问题的,还是有必要的,可是大家又不想这样敲这么多代码,有没有什么方法能够提高效率解决这个问题呢?

这时候我们可以使用动态代理解决上述问题

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

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class ArithmeticLoggingProxy {
// 要代理的对象
private Arithmetic target;
public ArithmeticLoggingProxy(Arithmetic target) {
this.target = target;
}
public Arithmetic getLoggingProxy() {
Arithmetic proxy = null;
// 代理对象由哪一个类加载器加载负责
ClassLoader loader = target.getClass().getClassLoader();
// 代理对象的类型,即其中有哪些方法
Class [] interfaces = new Class[]{Arithmetic.class};
// 当调用代理对象其中的方法时,该执行的代码
InvocationHandler h = new InvocationHandler() {
/*
* proxy:正在返回的那个代理对象,一般情况下,在invoke方法中都不使用该对象
* method:正在被调用的方法
* args:调用方法时,传入的参数
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
String methodName = method.getName();
// 日志
System.out.println("The method " + methodName + "begins with" + Arrays.asList(args));
// 执行方法
Object result = method.invoke(target, args);
// 日志
System.out.println("The method " + methodName + "ends with" + Arrays.asList(result));
return result;
}
};
proxy = (Arithmetic) Proxy.newProxyInstance(loader, interfaces, h);
return proxy;
}
}

上述代码把那些需要打印输出的日志代码通过动态代理包装了起来,当我们想改日志内容时只需要修改上述代码就能做到所有应用该代理的日志都跟着变。
不过,这种写法对一般程序员要求略高

AOP 简介

AOP(Aspect-Oriented Programming, 面向切面编程): 是一种新的方法论, 是对传统 OOP(Object-Oriented Programming, 面向对象编程) 的补充.
AOP 的主要编程对象是切面(aspect), 而切面模块化横切关注点.
在应用 AOP 编程时, 仍然需要定义公共功能, 但可以明确的定义这个功能在哪里, 以什么方式应用, 并且不必修改受影响的类. 这样一来横切关注点就被模块化到特殊的对象(切面)里.

AOP 的好处:

  • 每个事物逻辑位于一个位置, 代码不分散, 便于维护和升级
  • 业务模块更简洁, 只包含核心业务代码.

AOP 术语

  • 切面(Aspect): 横切关注点(跨越应用程序多个模块的功能)被模块化的特殊对象
  • 通知(Advice): 切面必须要完成的工作
  • 目标(Target): 被通知的对象
  • 代理(Proxy): 向目标对象应用通知之后创建的对象
  • 连接点(Joinpoint):程序执行的某个特定位置:如类某个方法调用前、调用后、方法抛出异常后等。连接点由两个信息确定:方法表示的程序执行点;相对点表示的方位。例如 ArithmethicCalculator#add() 方法执行前的连接点,执行点为 ArithmethicCalculator#add(); 方位为该方法执行前的位置
  • 切点(pointcut):每个类都拥有多个连接点:例如 ArithmethicCalculator 的所有方法实际上都是连接点,即连接点是程序类中客观存在的事务。AOP 通过切点定位到特定的连接点。类比:连接点相当于数据库中的记录,切点相当于查询条件。切点和连接点不是一对一的关系,一个切点匹配多个连接点,切点通过 org.springframework.aop.Pointcut 接口进行描述,它使用类和方法作为连接点的查询条件。

Spring AOP

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

在 Spring 中启用 AspectJ 注解支持

要在 Spring 应用中使用 AspectJ 注解, 必须在 classpath 下包含 AspectJ 类库: aopalliance.jar、aspectj.weaver.jar 和 spring-aspects.jar
将 aop Schema 添加到 <beans> 根元素中.
要在 Spring IOC 容器中启用 AspectJ 注解支持, 只要在 Bean 配置文件中定义一个空的 XML 元素 <aop:aspectj-autoproxy>
当 Spring IOC 容器侦测到 Bean 配置文件中的 <aop:aspectj-autoproxy> 元素时, 会自动为与 AspectJ 切面匹配的 Bean 创建代理.

用 AspectJ 注解声明切面

要在 Spring 中声明 AspectJ 切面, 只需要在 IOC 容器中将切面声明为 Bean 实例. 当在 Spring IOC 容器中初始化 AspectJ 切面之后, Spring IOC 容器就会为那些与 AspectJ 切面相匹配的 Bean 创建代理.

在 AspectJ 注解中, 切面只是一个带有 @Aspect 注解的 Java 类.
通知是标注有某种注解的简单的 Java 方法.

AspectJ 支持 5 种类型的通知注解:

  • @Before: 前置通知, 在方法执行之前执行
  • @After: 后置通知, 在方法执行之后执行
  • @AfterRunning: 返回通知, 在方法返回结果之后执行
  • @AfterThrowing: 异常通知, 在方法抛出异常之后
  • @Around: 环绕通知, 围绕着方法执行

前置通知

前置通知:在方法执行之前执行的通知
前置通知使用 @Before 注解, 并将切入点表达式的值作为注解值.

示例:
新建个包com.aop,src下新建个applicationContext.xml文件,aop下新建四个类:Main.java、Arithmetic.java、ArithmeticImpl.java、LoggingAspect.java
applicationContext.xml:

1
2
3
<context:component-scan base-package="com.aop"></context:component-scan>
<!-- 使用Aspectj注解起作用:自动为匹配的类生成代理对象 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

Arithmetic.java:

1
2
3
4
5
6
public interface Arithmetic {
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);
}

ArithmeticImpl.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Component
public class ArithmeticImpl implements Arithmetic {
@Override
public int add(int i, int j) {
// TODO Auto-generated method stub
int result = i + j;
return result;
}
@Override
public int sub(int i, int j) {
// TODO Auto-generated method stub
int result = i - j;
return result;
}
@Override
public int mul(int i, int j) {
// TODO Auto-generated method stub
int result = i * j;
return result;
}
@Override
public int div(int i, int j) {
// TODO Auto-generated method stub
int result = i / j;
return result;
}
}

Main.java:

1
2
3
4
5
6
7
8
9
10
11
public class Main {
public static void main(String[] args) {
// 1.获取IOC容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
// 2.从IOC获取bean实例
Arithmetic arithmetic = ctx.getBean(Arithmetic.class);
// 3.使用bean
int result = arithmetic.add(1, 2);
System.out.println("result: "+result);
}
}

LoggingAspect.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 把这个类声明为一个切面:需要把该类放到IOC容器中、再声明为一个切面
@Aspect
@Component
public class LoggingAspect {
// 声明该方法是一个前置通知:在目标方法开始之前执行
@Before("execution(public int com.aop.Arithmetic.add(int, int))")
public void beforeMethod() {
System.out.println("The method begins");
}
// 声明该方法是一个后置通知:在目标方法执行后(无论是否发生异常),都执行的通知
// 在后置通知中,还不能访问目标方法的执行结果
@After("execution(public int com.aop.Arithmetic.add(int, int))")
public void afterMethod() {
System.out.println("The method ends");
}
}

利用方法签名编写 AspectJ 切入点表达式

最典型的切入点表达式时根据方法的签名来匹配各种方法:
execution * com.atguigu.spring.ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 中声明的所有方法,第一个 代表任意修饰符及任意返回值. 第二个 代表任意方法. .. 匹配任意数量的参数. 若目标类与接口与该切面在同一个包中, 可以省略包名.
execution public * ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 接口的所有公有方法.
execution public double ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 中返回 double 类型数值的方法
execution public double ArithmeticCalculator.*(double, ..): 匹配第一个参数为 double 类型的方法, .. 匹配任意数量任意类型的参数
execution public double ArithmeticCalculator.*(double, double): 匹配参数类型为 double, double 类型的方法.

后置通知(上述示例已经包含了)

后置通知是在连接点完成之后执行的, 即连接点返回结果或者抛出异常的时候, 下面的后置通知记录了方法的终止.
一个切面可以包括一个或者多个通知.

返回通知

无论连接点是正常返回还是抛出异常, 后置通知都会执行. 如果只想在连接点返回的时候记录日志, 应使用返回通知代替后置通知.

异常通知

只在连接点抛出异常时才执行异常通知
将 throwing 属性添加到 @AfterThrowing 注解中, 也可以访问连接点抛出的异常. Throwable 是所有错误和异常类的超类. 所以在异常通知方法可以捕获到任何错误和异常.
如果只对某种特殊的异常类型感兴趣, 可以将参数声明为其他异常的参数类型. 然后通知就只在抛出这个类型及其子类的异常时才被执行.

环绕通知

环绕通知是所有通知类型中功能最为强大的, 能够全面地控制连接点. 甚至可以控制是否执行连接点.
对于环绕通知来说, 连接点的参数类型必须是 ProceedingJoinPoint . 它是 JoinPoint 的子接口, 允许控制何时执行, 是否执行连接点.
在环绕通知中需要明确调用 ProceedingJoinPoint 的 proceed() 方法来执行被代理的方法. 如果忘记这样做就会导致通知被执行了, 但目标方法没有被执行.
注意: 环绕通知的方法需要返回目标方法执行之后的结果, 即调用 joinPoint.proceed(); 的返回值, 否则会出现空指针异常

Newer Post

Spring4.0学习12--在xml文件中配置AOP

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

继续阅读
Older Post

Spring4.0学习10

泛型依赖注入Spring 4.x 中可以为子类注入子类对应的泛型类型的成员变量的引用 示例: 新建beans-generic.di.xml,新建com.generic.di包,包下面新建6个类,分别是Main.java,User.java,BaseService.java,BaseReposito …

继续阅读