Spring Boot 的 AOP 的简单实现
Spring Boot 工程的依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
完成一个切面类
package com.example.spring_aop.aspect;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class Logger {
@Pointcut("execution(* com.example.spring_aop.service..*.*(..))")
public void pointCut() {
}
@Before("pointCut()")
public void before() {
System.out.println("before");
}
@After("pointCut()")
public void after() {
System.out.println("after");
}
}
完成 service 类的写(由于是简单实例 本文的 service 也简单)
package com.example.spring_aop.service;
import org.springframework.stereotype.Service;
@Service
public class HelloWorld {
public void sayHello(){
System.out.println("Hello World!");
}
}
编写测试类
package com.example.spring_aop;
import com.example.spring_aop.service.HelloWorld;
import org.junit.jupiter.api.Test;
import org.omg.CORBA.CTX_RESTRICT_SCOPE;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
@SpringBootTest
class SpringAopApplicationTests {
@Test
void contextLoads() {
}
@Test
void testAspect() {
ApplicationContext context = SpringApplication.run(SpringAopApplication.class);
HelloWorld helloWorld = context.getBean(HelloWorld.class);
for (int i = 0; i < 10; i++) {
helloWorld.sayHello();
}
}
}
输出结果
