创建一个Dog类,向其中加入eat0方法。使用 AOP在eatQ方法前后添加喝水的drink(方法,之后添加runQ跑的方法。(使用XML方式或注解 方式实现)相关分别建在哪些文件夹下,运行出结果
时间: 2023-06-13 07:08:10 浏览: 36
使用注解方式实现:
1. 创建Dog类:
```java
public class Dog {
public void eat() {
System.out.println("吃饭");
}
}
```
2. 创建切面类:
```java
@Aspect
@Component
public class DogAspect {
@Before("execution(* Dog.eat())")
public void drink() {
System.out.println("喝水");
}
@After("execution(* Dog.eat())")
public void run() {
System.out.println("跑步");
}
}
```
3. 在Spring配置文件中开启AOP:
```xml
<aop:aspectj-autoproxy />
<context:component-scan base-package="com.example" />
```
4. 运行测试代码:
```java
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Dog dog = context.getBean(Dog.class);
dog.eat();
}
}
```
输出结果:
```
喝水
吃饭
跑步
```
注解方式的相关代码都放在了同一个文件夹下,即与Dog类和Test类在同一个包下。
如果使用XML方式实现,需要创建一个切面类和一个XML配置文件。
1. 创建切面类:
```java
public class DogAspect {
public void drink() {
System.out.println("喝水");
}
public void run() {
System.out.println("跑步");
}
}
```
2. 创建XML配置文件:
```xml
<bean id="dog" class="com.example.Dog" />
<bean id="dogAspect" class="com.example.DogAspect" />
<aop:config>
<aop:aspect id="dogAspect" ref="dogAspect">
<aop:before method="drink" pointcut="execution(* com.example.Dog.eat())" />
<aop:after method="run" pointcut="execution(* com.example.Dog.eat())" />
</aop:aspect>
</aop:config>
```
3. 运行测试代码同样需要在Spring配置文件中开启AOP:
```xml
<aop:aspectj-autoproxy />
```
4. 运行测试代码:
```java
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Dog dog = context.getBean(Dog.class);
dog.eat();
}
}
```
输出结果同样为:
```
喝水
吃饭
跑步
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)