普通AOP开发(XML方式)
一、使用AOP目的
使用AOP的目的:就是对类里面的方法进行增强
- 前置增强:在方法执行之前加入相关代码
- 后置增强:在方法执行之后加入相关代码
- 环绕增强:前置增强和后置增强
- 异常增强:在目标方法发生异常时加入相关代码
二、AOP开发中的概念
- JoinPoint(连接点):所谓连接点是指哪些被拦截的点,而spring 中这些点就是指方法,因为spring只支持方法类型的连接点。
- PointCut(切入点):所谓切入点就是指我们要对那些JoinPoint 进行拦截的定义。
- Advice(通知/增强):所谓通知/增强,就是指拦截到JoinPoint后需要完成的事情,它分为前置通知/增强,后置通知/增强,异常通知/增强,最终通知/增强,环绕通知/增强(切面要完成的功能)
- Introduction(引介):引介是一种特殊的Advice,在不修改代码的前提下,引介可以在运行期为类动态的添加一些方法或Field。
- Target(目标):代理对象的目标对象(要增强的类)
- Weaving(织入):把 Advice 应用到 Target 的过程
- Proxy(代理):一个类被 AOP 注入增强后,就产生了一个结果代理类
- Aspect(切面):是 PointCut 和Advice(Introduction)的结合
三、示例
1. 创建项目并导包
2. 创建Person
3. 创建applicationContext.xml
<!-- 导入头文件 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
4. 前置通知
- 创建MyBeforeAdvise
- 配置applicationContext.xml
- 测试
5. 后置通知
- 创建MyAfterAdvise
- 配置applicationContext.xml
6. 环绕通知
- 第一种环绕通知
|-- 创建MyBeforeAdvise、MyAfterAdvise
|-- 配置applicationContext.xml
|-- 测试
- 第二种环绕通知
|-- 创建MyAroundAdvise
package com.lasing.advise;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* 环绕通知
* */
public class MyAroundAdvise implements MethodInterceptor{
/**
* MethodInvocation
* 目标方法执行对象
* */
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
before();
Object proceed = invocation.proceed();
after();
return proceed;
}
/**
* 执行前做的事
* */
public void before() {
System.out.println("饭前水果...");
}
/**
* 执行后做的事
* */
public void after() {
System.out.println("饭后甜点...");
}
}
|-- 配置applicationContext.xml
|-- 测试
7. 异常通知
- 手动设置一个异常
- 创建MyExceptionAdvise
- 配置applicationContext.xml
- 测试