AOP的相关术语
Joinpoint(连接点)
-- 所谓连接点是指那些被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点
Pointcut(切入点)
-- 所谓切入点是指我们要对哪些Joinpoint进行拦截的定义
Advice(通知)
-- 所谓通知是指拦截到Joinpoint之后所要做的事情就是通知
Introduction(引介)
-- 引介是一种特殊的通知在不修改类代码的前提下, Introduction可以在运行期为类动态地添加一些方法或Field
Target(目标对象)
-- 代理的目标对象
Weaving(织入)
--是指把通知应用到目标对象来创建新的代理对象的过程
Proxy(代理)
-- 一个类被AOP织入通知后,就产生一个结果代理类
Aspect(切面)
-- 是切入点和通知的结合,以后咱们自己来编写和配置的
spring AOP快速入门
添加spring和aop的依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<!--AOP-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
编写UserService接口和UserServiceImpl实现类,在此省略
编写AOP的切面类
public class Aspect {
public void transaction(){
System.out.println("开启事务...");
}
}
编写配置文件
<bean id="userService" class="com.hw.learn1.proxy.impl.UserServiceImpl"/>
<bean id="aspect" class="com.hw.learn1.aspect.Aspect"/>
<aop:config>
<!-- 引入切面类 -->
<aop:aspect ref="aspect">
<!--
定义通知类型:切面类的方法和切入点的表达式
切入点表达式的格式如下:
execution([修饰符] 返回值类型 包名.类名.方法名(参数))
返回值类型是不能省略不写的,根据你的方法来编写返回值。可以使用 * 代替
可以使用*..*来代替包
*来代替类名
..代替任意参数
-->
<!--
通知类型可写参数
before -前置通知(在目标类的方法执行之前执行)
after -最终通知(在目标类的方法执行之后执行,如果程序出现了异常,最终通知也会执行)
after-returning -后置通知(方法正常执行后的通知)
after-throwing -异常抛出通知(在抛出异常后通知)
around -环绕通知(方法的执行前后执行)
使用环绕通知,目标的方法默认不执行,需要使用ProceedingJoinPoint对来让目标对象的方法执行
-->
<aop:before method="transaction" pointcut="execution(public * *..*.UserServiceImpl.save(..))"/>
</aop:aspect>
</aop:config>
编写测试代码
@Test
public void run(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContextaop.xml");
// 通过工厂获得类:
UserService userService = (UserService) applicationContext.getBean("userService");
userService.save();
}