springboot切面学习
时间: 2023-11-11 11:57:54 浏览: 57
Spring Boot 中使用切面可以在不修改原有代码的情况下实现对某些方法的增强,比如添加日志、性能监控等功能。下面是一个简单的示例:
首先定义一个切面类,使用 @Aspect 注解标识这是一个切面:
```
@Aspect
@Component
public class LogAspect {
// 定义一个切点,表示需要增强的方法
@Pointcut("execution(* com.example.demo.controller..*(..))")
public void pointcut() {}
// 定义方法,表示具体的增强逻辑
@Before("pointcut()")
public void before(JoinPoint joinPoint) {
System.out.println("调用方法:" + joinPoint.getSignature().getName());
}
}
```
上面的代码表示,对 com.example.demo.controller 包及其子包中的所有方法进行增强,在方法执行前输出日志。
然后在启动类上加上 @EnableAspectJAutoProxy 注解开启自动代理:
```
@SpringBootApplication
@EnableAspectJAutoProxy
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```