持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情
Spring中的AOP
AspectJ框架【AOP框架】
- AspectJ框架是Java社区中最完整最流行的AOP框架
- 在Spring2.0以上的版本中,可以使用基于AspectJ注解或基于XML配置的AOP。
使用AspectJ步骤
-
导入相关jar包
<!-- 添加AspectJ--> <!--spirng-aspects的jar包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.3.1</version> </dependency> -
配置文件
- 开启组件扫描
- 开启AspectJ注解支持
<!-- 开启组件扫描--> <context:component-scan base-package="com.atguigu"></context:component-scan> <!-- 开启AspectJ注解支持--> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> -
切面类(MyLogging类)添加注解
@Component //标识当前类为一个组件。 @Aspect //将当前类标识为切面类(非核心业务提取类)。 -
在切面类中添加通知注解
@Component @Aspect public class MyLogging { @Before(value = "execution(public int Spring.AOP.CalcImpl.add(int ,int))") public void beforeMethod(JoinPoint joinPoint){ //获取当前方法名称 String name = joinPoint.getSignature().getName(); //获取方法形参 Object[] args = joinPoint.getArgs(); System.out.println("当前调用"+ name + "方法,参数是"+ Arrays.toString(args)); } } -
测试
@Test public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Calc calc = context.getBean("calc", Calc.class); //错误的,代理对象不能转换为目标对象【代理对象与目标对象是兄弟关系】 //CalcImpl calc = context.getBean("calc", CalcImpl.class); calc.add(1,2); }
\
Spring中AOP概述
-
AOP:Aspect-Oriented Programming,面向切面编程【面向对象一种补充】
-
优势:
- 解决代码分散问题
- 解决代码混乱问题
-
-
OOP:Object-Oriented Programming,面向对象编程
Spring中AOP相关术语
- 横切关注点:非核心业务代码【日志】,称之为横切关注点
- 切面(Aspect) :将横切关注点提取到类中,这个类称之为切面类
- 通知(Advice) :将横切关注点提取到类中之后,横切关注点更名为:通知
- 目标(Target):目标对象,指的是需要被代理的对象【实现类(CalcImpl)】
- 代理(Proxy):代理对象可以理解为:中介
- 连接点(Joinpoint):通知方法需要指定通知位置,这个位置称之为:连接点【通知之前】
- 切入点(pointcut) :通知方法需要指定通知位置,这个位置称之为:切入点【通知之后】