以下是一个使用Spring Boot AOP的简单案例:
假设我们有一个UserService接口,它包含了两个方法:getUserById和createUser。我们希望在每个方法执行前后打印日志。
首先,我们需要创建一个切面类,用于定义我们的切面逻辑。在切面类上加上@Aspect注解,表示它是一个切面类。然后,我们可以使用@Before和@After注解来定义方法执行前后的逻辑。
@Aspect
@Component
public class LoggingAspect {
private Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
@Before("execution(* com.example.service.UserService.*(..))")
public void logBefore(JoinPoint joinPoint) {
logger.info("Before executing method: {}", joinPoint.getSignature().getName());
}
@After("execution(* com.example.service.UserService.*(..))")
public void logAfter(JoinPoint joinPoint) {
logger.info("After executing method: {}", joinPoint.getSignature().getName());
}
}
接下来,我们需要在配置类上加上@EnableAspectJAutoProxy注解,开启AOP功能。
@SpringBootApplication
@EnableAspectJAutoProxy
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
最后,我们可以在UserController中注入UserService,并调用相关方法进行测试。
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@PostMapping("/user")
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
}
当我们访问/user/{id}
和/user
接口时,控制台将会打印出方法执行前后的日志信息。
这是一个简单的Spring Boot AOP案例。你可以根据实际业务需求,在切面类中添加更多的逻辑。