创建一个Dog类,向其中加入eat()方法。使用 AOP在eat()方法前后添加喝水的drink(方法,之后添加run()跑的方法。(使用注解 方式实现)相关分别建在哪些文件夹下,运行出结果
时间: 2023-06-13 20:05:58 浏览: 211
java aop拦截方法类前后添加日志
代码实现:
1. 创建一个Dog类,加入eat()方法:
```java
public class Dog {
public void eat() {
System.out.println("Dog is eating.");
}
}
```
2. 使用注解方式实现AOP:
```java
@Aspect
@Component
public class DogAspect {
@Before("execution(* Dog.eat())")
public void drink() {
System.out.println("Dog is drinking water.");
}
@After("execution(* Dog.eat())")
public void run() {
System.out.println("Dog is running.");
}
}
```
3. 在Spring Boot的启动类上加上@EnableAspectJAutoProxy注解开启AOP:
```java
@SpringBootApplication
@EnableAspectJAutoProxy
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
运行结果:
```
Dog is drinking water.
Dog is eating.
Dog is running.
```
阅读全文