当前位置: 移动技术网 > IT编程>开发语言>Java > 最全的Spring AOP

最全的Spring AOP

2018年12月24日  | 移动技术网IT编程  | 我要评论

1.什么是aop?

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

2.为什么需要aop?

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

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

使用aop的好处是:

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

 

3.aop术语

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

4.如何使用aop?

aspectj:java 社区里最完整最流行的 aop 框架.在 spring2.0 以上版本中, 可以使用基于 aspectj 注解或基于 xml 配置的 aop。

4.1 在spring中启用aspectj注解支持

(1)在classpath下添加jar包

要在spring应用中使用aspectj注解,需要添加的jar包有(包含spring的基础jar包):

  • com.springsource.org.aopalliance-1.0.0.jar
  • com.springsource.org.aspectj.weaver-1.6.8.release.jar
  • commons-logging-1.1.3.jar
  • spring-aop-4.0.0.release.jar
  • spring-aspects-4.0.0.release.jar
  • spring-beans-4.0.0.release.jar
  • spring-context-4.0.0.release.jar
  • spring-core-4.0.0.release.jar
  • spring-expression-4.0.0.release.jar

(2)在配置文件中加入aop的命名空间

(3)要在 spring ioc 容器中启用 aspectj 注解支持, 只要在 bean 配置文件中定义一个空的 xml 元素 <aop:aspectj-autoproxy>,当 spring ioc 容器侦测到 bean 配置文件中的 <aop:aspectj-autoproxy> 元素时, 会自动为与 aspectj 切面匹配的 bean 创建代理.

4.2 用aspectj注解声明切面

(1)要在spring中声明aspectj切面,需要在ioc容器中将切面声明为bean实例,即加入@component注解;

(2)在aspectj注解中,切面是一个带有@aspect注解的java类,即加入@aspect注解;

4.3 在类中声明各种通知

(1)声明一个方法;

(2)在方法前加入通知注解。

5.aspectj 支持 5 种类型的通知注解

  • @before: 前置通知, 在方法执行之前执行
  • @after: 后置通知, 在方法执行之后执行
  • @afterrunning: 返回通知, 在方法返回结果之后执行
  • @afterthrowing: 异常通知, 在方法抛出异常之后
  • @around: 环绕通知, 围绕着方法执行

5.1 前置通知

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

示例代码:

定义接口:arithmeticcalculator.java

package com.java.spring.aop.impl;

public interface arithmeticcalculator {
    int add(int i,int j);
    int sub(int i,int j);
    int mul(int i,int j);
    int div(int i,int j);
}

接口的实现类:arithmeticcalculatorimpl.java

package com.java.spring.aop.impl;
import org.springframework.stereotype.component;

@component("arithmeticalculator")
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;
	}
}

日志loggingaspect.java

package com.java.spring.aop.impl;

import java.util.arrays;
import java.util.list;
import org.aspectj.lang.joinpoint;
import org.aspectj.lang.annotation.aspect;
import org.aspectj.lang.annotation.before;
import org.springframework.stereotype.component;
@aspect
@component
public class loggingaspect {
	@before("execution(public int com.java.spring.aop.impl.arithmeticcalculator.*(int, int))")
	public void beforemethod(joinpoint joinpoint){
		string methodname=joinpoint.getsignature().getname();
		list<object> args=arrays.aslist(joinpoint.getargs());
		system.out.println("the method "+methodname+" begins with args "+args);
	}
	
}

在applicationcontext.xml中进行配置:

<context:component-scan base-package="com.java.spring.aop.impl"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

测试:

main.java

package com.java.spring.aop.impl;

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");
		arithmeticcalculator ac=(arithmeticcalculator) ctx.getbean("arithmeticalculator");
		int result1=ac.add(123, 10);
		system.out.println(result1);
		int result2=ac.sub(123, 10);
		system.out.println(result2);
	}
}

运行后输出:

the method add begins with args [123, 10]
133
the method sub begins with args [123, 10]
113

(1)loggingaspect.java中,

@before("execution(public int com.java.spring.aop.impl.arithmeticcalculator.*(int, int))")
public void beforemethod(joinpoint joinpoint){...}

标示beforemethod()方法是前置通知,切点表达式表示执行arithmeticcalculator接口中参数为两个int类型,并且方法修饰符为public和返回值为int类型的所有方法。

最典型的切入点表达式时根据方法的签名来匹配各种方法:

  • execution * com.java.spring.aop.impl.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 类型的方法.

(2)让通知访问当前连接点的细节。可以在通知方法中声明一个类型为 joinpoint 的参数. 然后就能访问链接细节. 如方法名称和参数值.

string methodname=joinpoint.getsignature().getname();
list<object> args=arrays.aslist(joinpoint.getargs());

5.2 后置通知

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

@after("execution(public int com.java.spring.aop.impl.arithmeticcalculator.*(int, int))")
	public void aftermethod(joinpoint joinpoint){
		string methodname=joinpoint.getsignature().getname();
		list<object> args=arrays.aslist(joinpoint.getargs());
		system.out.println("the method "+methodname+" ends with args "+args);
	}

5.3 返回通知

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

在返回通知中, 只要将 returning 属性添加到 @afterreturning 注解中, 就可以访问连接点的返回值. 该属性的值即为用来传入返回值的参数名称. 而且必须在通知方法的签名中添加一个同名参数. 在运行时, spring aop 会通过这个参数传递返回值.

@afterreturning(value="execution(public int com.java.spring.aop.impl.arithmeticcalculator.*(int, int))",
			returning="result")
	public void reutrnmethod(joinpoint joinpoint,object result){
		string methodname=joinpoint.getsignature().getname();
		list<object> args=arrays.aslist(joinpoint.getargs());
		system.out.println("the method "+methodname+" ends with args "+args+"and the result is "+result);
	}

5.4 异常通知

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

@afterthrowing(value="execution(public int com.java.spring.aop.impl.arithmeticcalculator.*(int, int))",
			throwing="e")
	public void afterthrowing(joinpoint joinpoint,exception e){
		string methodname=joinpoint.getsignature().getname();
		list<object> args=arrays.aslist(joinpoint.getargs());
		system.out.println("the method "+methodname+" occurs "+args+e);
	}

5.5 环绕通知

环绕通知是所有通知类型中功能最为强大的, 能够全面地控制连接点. 甚至可以控制是否执行连接点。对于环绕通知来说, 连接点的参数类型必须是 proceedingjoinpoint ,可以决定是否执行目标方法。它是 joinpoint 的子接口, 允许控制何时执行, 是否执行连接点。在环绕通知中需要明确调用 proceedingjoinpoint 的 proceed() 方法来执行被代理的方法. 如果忘记这样做就会导致通知被执行了, 但目标方法没有被执行。

@around("execution(public int com.java.spring.aop.impl.arithmeticcalculator.*(int, int))")
	public object aroundmethod(proceedingjoinpoint pjd){
		object result=null;
		string methodname=pjd.getsignature().getname();
		try {
			//前置通知
			system.out.println("the method "+methodname+" begins with args "+arrays.aslist(pjd.getargs()));
			//执行目标方法
			result=pjd.proceed();
			//返回通知
			system.out.println("the method "+"ends with "+result);
		} catch (throwable e) {
			//异常通知
			system.out.println("the method occurs exception "+e);
		}
		//后置通知
		system.out.println("the method ends");
		return result;
	}

6.切面的优先级

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

@aspect
@order(0)
@component
public class loggingaspect {}

7.重用切入点表达式

在 aspectj 切面中, 可以通过 @pointcut 注解将一个切入点声明成简单的方法. 切入点的方法体通常是空的。后面的其他通知直接使用方法名来引用当前的接入点表达式。

切入点方法的访问控制符同时也控制着这个切入点的可见性. 如果切入点要在多个切面中共用, 最好将它们集中在一个公共的类中. 在这种情况下, 它们必须被声明为 public. 在引入这个切入点时, 必须将类名也包括在内. 如果类没有与这个切面放在同一个包中, 还必须包含包名.

//定义一个方法,用于声明一个切入点表达式
	@pointcut("execution(public int com.java.spring.aop.impl.arithmeticcalculator.*(int, int))")
	public void declarejointpointexpression(){}
	@before("declarejointpointexpression()")
	public void beforemethod(joinpoint joinpoint){
		string methodname=joinpoint.getsignature().getname();
		list<object> args=arrays.aslist(joinpoint.getargs());
		system.out.println("the method "+methodname+" begins with args "+args);
	}

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网