提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
Spring AOP 面向切面编程的一些方法。
一、AOP中术语
- 连接点 JointPoint:可以织入切面的位置。
- 切点 Pointcut:真正织入切面的方法。
- 通知 Advice:又叫增强,具体织入的代码。(前置,后置,环绕,异常,最终通知)
- 切面 Aspect:切点+通知 =切面
- 织入 Weaving:将通知应用到目标对象上的过程。
- 代理对象 Proxy:目标对象被织入通知后产生的新对象。
- 目标对象 Target:被织入统治的对象。
二、Spring实现AOP的3种方式
- 第一种:Spring框架结合AspectJ框架实现的AOP,基于注解方式。
- 第二种:Spring框架结合AspectJ框架实现的AOP,基于XML方式。
- 第三种:Spring框架自己实现的AOP,基于XML配置方式。
1.基于注解的方式
引入AspectJ依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>6.1.13</version>
</dependency>
全注解开发
@Configuration //代替spring.xml文件
@ComponentScan({"com.powernode....."}) //组件扫描注释
@EnableAspectJAutoProxy(proxyTargetClass=True) //启用自动代理
public class Spring6Config{
}
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Spring6Config);
注解解释: @Aspect(): 表示切面类 @Order() 可以对切面类进行排序
@Before: 前置通知
@AfterReturning: 后置通知
@Around: 环绕通知
*使用环绕通知方法需要参数 ProceedingJoinPoint 调用该参数的proceed()方法执行目标方法。
@AfterThrowing: 异常通知
@After: 最终通知 finally语句块中
若是发生异常,则后环绕与后置通知不执行。
切入语句:execution([public] * com.exmple..*(..))
[方法权限] (返回值) (类名) (方法名) (参数) 异常
为了实现切点表达式代码的复用可以声明方法如:
@Pointcut("execution表示式")
public void generalPointCut(){
}
//目标方法引用
@Before("generalPointCut()")
public void beforeAdvice(){
System.out.println("前置通知");
}
2.基于XML配置文件
<bean id="userService" class="com.powernode.spring6.service.UserService"></bean>
<bean id="timerService" class="com.powernode.spring6.service.TimerService"></bean>
<!--aop的配置>
<aop:config>
<!--切点表达式-->
<aop:pointcut id="mypointcut" expression="execution(* com.powernode.spring.service..*(..))"/>
<aop:aspect ref="timerAspect">
<aop:around method="aroundAdvice" pointcut-ref="mypointcut" />
</aop:aspect>
</aop:config>