在SpringBoot中使用AOP切面编程

如果有对SpringAOP不太懂的小伙伴可以查看我之前的Spring学习系列博客
SpringBoot的出现,大大地降低了开发者使用Spring的门槛,我们不再需要去做更多的配置,而是关注于我们的业务代码本身,在SpringBoot中使用AOP有两种方式:

一、使用原生的SpringAOP(不是很推荐,但这是最基本的应用)

第1步,引入Aspect的相关依赖

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.1</version>
</dependency>
<!--织入器-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.1</version>
</dependency>

第二步,在SpringBoot的配置类中开启AspectJ代理

1
2
3
4
5
6
7
8
9
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class SpringbootLearnApplication {

public static void main(String[] args) {
SpringApplication.run(SpringbootLearnApplication.class, args);
}

}

第三步,写代码

  • 创建一个目标类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 教师类
*/
@Component
public class HighTeacher {
private String name;
private int age;

public void teach(String content) {
System.out.println("I am a teacher,and my age is " + age);
System.out.println("开始上课");
System.out.println(content);
System.out.println("下课");
}

...getter and setter
}
  • 切面类,用来配置切入点和通知
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 切面类,用来写切入点和通知方法
*/
@Component
@Aspect
public class AdvisorBean {
/*
切入点
*/
@Pointcut("execution(* teach*(..))")
public void teachExecution() {
}

/************以下是配置通知类型,可以是多个************/
@Before("teachExecution()")
public void beforeAdvice(ProceedingJoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
args[0] = ".....你们体育老师生病了,我们开始上英语课";
Object proceed = joinPoint.proceed(args);

return proceed;
}
}
  • 测试类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package cn.lyn4ever.learn.springbootlearn;

import cn.lyn4ever.learn.springbootlearn.teacher.HighTeacher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = SpringbootLearnApplication.class)
@RunWith(SpringRunner.class)
public class SpringbootLearnApplicationTests {

@Autowired
HighTeacher highTeacher;

@Test
public void contextLoads() {
highTeacher.setAge(12);
highTeacher.teach("大家好,我们大家的体育老师,我们开始上体育课");
}
}

结果就是大家想要的,体育课被改成了英语课
结果就是大家想要的,体育课被改成了英语课

二、使用Springboot-start-aop(推荐)

在pom文件中引入

1
2
3
4
<dependency>  
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

上边这一个依赖,就是代替了第一种方式中的第一步和第二步合并了而已,其他的代码不变

CodeCraft编程工艺