这一节,来探索下AOP的相关概念。
一、AOP概念
OOP(Object Oriented Programming,面向对象编程)引入封装、继承、多态等概念来建立一种对象层次结构,用于模拟公共行为的一个集合,整个是一个纵向关系。
在软件开发中,我们还会用到许多功能,如日志、事务管理,这些功能代码,往往散落于应用对象各处,那么日志等与业务对象之间可以看作是横向的关系。
传统编码方式会带来一个问题:一个业务对象中,会存在大量的非业务相关代码。这样在后期维护,是十分不便的。
这样就引出了AOP概念:AOP(Aspect Oriented Programming),即面向切面编程,可以说是OOP(Object Oriented Programming,面向对象编程)的补充和完善。它利用一种称为"横切"的技术,剖解开封装的对象内部,并将那些影响了多个类的公共行为封装到一个可重用模块,并将其命名为"Aspect",即切面。所谓"切面",简单说就是那些与业务无关,却为业务模块所共同调用的逻辑或责任封装起来,便于减少系统的重复代码,降低模块之间的耦合度,并有利于未来的可操作性和可维护性。
使用"横切"技术,AOP把软件系统分为两个部分:核心关注点和横切关注点。业务处理的主要流程是核心关注点,与之关系不大的部分是横切关注点。横切关注点的一个特点是,他们经常发生在核心关注点的多处,而各处基本相似,比如权限认证、日志、事物。AOP的作用在于分离系统中的各种关注点,将核心关注点和横切关注点分离开来。
AOP实现了横切关注点与业务对象之间的解耦。
如下图所示:
几个核心概念:
- 横切关注点
散布于应用多处的功能,如:日志、安全、事务管理、异常处理等。 - 切面(aspect)
类是对物体特征的抽象,切面就是对横切关注点的抽象。 - 连接点(joinpoint)
在应用执行过程中,能够插入切面的一个点。比如:调用方法时、抛出异常时。
(因为Spring只支持方法类型的连接点,所以在Spring中连接点指的就是被拦截到的方法。) - 切点(pointcut)
对连接点进行拦截的定义。(即哪些连接点需要插入切面。) - 通知(advice)
切面的工作。指拦截到连接点之后要执行的代码:可分为前置、后置、异常、最终、环绕通知五类。 - 织入(weave)
将切面应用到目标对象并导致代理对象创建的过程。 - 引入(introduction)
在不修改代码的前提下,引入可以在运行期为类动态地添加一些方法或字段。 - 目标对象
代理的目标对象
二、Spring中AOP的实现
Spring注解式实现,可分三步走:
1.xml中开启注解
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="cn.nep.aop"></context:component-scan>
<!-- 使 AspectJ 的注解起作用 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
2.业务对象交由spring管理
算术类ArithmeticCalculatorImpl.java
@Component("arithmeticCalculator")
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
private String msg = "sss";
@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;
}
}
接口 ArithmeticCalculator.java
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);
}
3.定义切面类
日志切面类 LoggingAspect.java
//通过添加 @Aspect 注解声明一个 bean 是一个切面!
@Aspect
@Component
public class LoggingAspect {
// 切点
@Pointcut("execution(public int cn.nep.aop.ArithmeticCalculator.div(int, int))")
public void point01(){}
/* */
// 前置通知,可进行日志记录
@Before("point01()")
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(* cn.nep.aop.*.*(..))")
public void afterMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " ends");
}
/**
* 环绕通知,可对参数进行验证
* @param pjp
* @return
*/
@Around("point01()")
public Object arround(ProceedingJoinPoint pjp){
System.out.println("==="+pjp.getSignature().getClass());
Object rtValue = null;
System.out.println(pjp.getTarget().getClass());
try {
Object[] args = pjp.getArgs();//得到方法执行所需的参数
int arg2 = (int)args[1];
if(arg2 == 0){
System.out.println("参数有误,被除数不能为0!");
return -1;
}
rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
}catch (Exception e){
e.printStackTrace();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return rtValue;
}
}
测试
/**
* spring 实现aop
*/
public static void test02(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("cn/nep/aop/applicationContext-aop.xml");
ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator");
System.out.println(arithmeticCalculator.getClass().getName());
int result = arithmeticCalculator.add(11, 12);
System.out.println("result:" + result);
result = arithmeticCalculator.div(21, 2);
System.out.println("result:" + result);
}
三、自定义实现AOP功能(动态代理)
在java中,动态代理是实现AOP的一种方式。详情见代码。
动态代理类 ArithmeticCalculatorLoggingProxy.java
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;
}
}
使用
/**
* 动态代理模式,实现aop
*/
public static void test(){
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);
}