文章目录
前言
最近在B站学习 Spring注解驱动 相关内容,老师讲得挺好的,但是笔记都在代码的注释里面,而且有些笔记可以完善一下,所以就新开一个专栏专门记录一下这个课程的一些学习笔记。
在之前学习 若依
以及 RuoYi-Vue-Plus
框架的时候,有整理过关于 AOP 的内容(【若依】开源框架学习笔记04 - AOP日志实现),但是只是停留在框架层面上的应用,而 AOP 又是 Spring Framework
中的核心内容,几乎每一个 Spring 教学视频或者文章都会有所涉及,所以理解这部分内容也显得尤为重要。
说明:这套视频时间比较久,用的版本是 Spring 4.X,目前 Spring 5.X 使用较多,为了和视频保持一致,所以代码都是源代码,即基于Spring 4.X。
参考资料
-
Spring 官方文档(Version 5.3.13) - Aspect Oriented Programming with Spring
-
视频 - AOP功能测试
-
笔记截图:
功能搭建
1、导入 AOP 模块
再次说明:视频是基于 Spring 4.X 的版本,如果用 Spring 5.X,此部分内容区别不大。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
2、定义一个业务逻辑类(MathCalculator)
public class MathCalculator {
public int div(int i,int j){
System.out.println("MathCalculator...div...");
return i/j;
}
}
3、定义一个日志切面类(LogAspects)
@Aspect
注解指定该类为切面类
@Aspect
public class LogAspects {
//抽取公共的切入点表达式
//1、本类引用
//2、其他的切面引用
@Pointcut("execution(public int com.atguigu.aop.MathCalculator.*(..))")
public void pointCut(){};
//@Before在目标方法之前切入;切入点表达式(指定在哪个方法切入)
@Before("pointCut()")
public void logStart(JoinPoint joinPoint){
Object[] args = joinPoint.getArgs();
System.out.println(""+joinPoint.getSignature().getName()+"运行。。。@Before:参数列表是:{"+Arrays.asList(args)+"}");
}
@After("com.atguigu.aop.LogAspects.pointCut()")
public void logEnd(JoinPoint joinPoint){
System.out.println(""+joinPoint.getSignature().getName()+"结束。。。@After");
}
//JoinPoint一定要出现在参数表的第一位
@AfterReturning(value="pointCut()",returning="result")
public void logReturn(JoinPoint joinPoint,Object result){
System.out.println(""+joinPoint.getSignature().getName()+"正常返回。。。@AfterReturning:运行结果:{"+result+"}");
}
@AfterThrowing(value="pointCut()",throwing="exception")
public void logException(JoinPoint joinPoint,Exception exception){
System.out.println(""+joinPoint.getSignature().getName()+"异常。。。异常信息:{"+exception+"}");
}
}
4、配置切面类和业务逻辑类
@Configuration
public class MainConfigOfAOP {
//业务逻辑类加入容器中
@Bean
public MathCalculator calculator(){
return new MathCalculator();
}
//切面类加入到容器中
@Bean
public LogAspects logAspects(){
return new LogAspects();
}
}
5、开启基于注解的 AOP 模式
即加入注解 @EnableAspectJAutoProxy
功能测试
public class IOCTest_AOP {
@Test
public void test01(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfAOP.class);
//1、不要自己创建对象
// MathCalculator mathCalculator = new MathCalculator();
// mathCalculator.div(1, 1);
MathCalculator mathCalculator = applicationContext.getBean(MathCalculator.class);
mathCalculator.div(1, 0);
applicationContext.close();
}
}