【Spring 注解驱动】学习笔记 01 - Spring AOP(一)AOP 相关功能搭建

前言

最近在B站学习 Spring注解驱动 相关内容,老师讲得挺好的,但是笔记都在代码的注释里面,而且有些笔记可以完善一下,所以就新开一个专栏专门记录一下这个课程的一些学习笔记。

在之前学习 若依 以及 RuoYi-Vue-Plus 框架的时候,有整理过关于 AOP 的内容(【若依】开源框架学习笔记04 - AOP日志实现),但是只是停留在框架层面上的应用,而 AOP 又是 Spring Framework 中的核心内容,几乎每一个 Spring 教学视频或者文章都会有所涉及,所以理解这部分内容也显得尤为重要。

说明:这套视频时间比较久,用的版本是 Spring 4.X,目前 Spring 5.X 使用较多,为了和视频保持一致,所以代码都是源代码,即基于Spring 4.X。

参考资料

功能搭建

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();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MichelleChung

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值