使用Spring AOP实现租客租到满意的房子 需求: 1、 编写房东类Landlord.java文件,包含一个属性房东的名字name和一个方法house 2、 编写中介代理类Agent.java,包含签合同和完成租房两个方法 3、 编写application-context.xml配置文件 4、 编写相应的测试类,得到结果
时间: 2024-03-01 12:52:50 浏览: 30
好的,我可以为您提供一个基本的实现思路。
1. Landlord 类
```java
public class Landlord {
private String name;
public Landlord(String name) {
this.name = name;
}
public void house() {
System.out.println(name + "正在出租房子");
}
}
```
2. Agent 类
```java
public class Agent {
public void signContract() {
System.out.println("签订租房合同");
}
public void rentHouse() {
System.out.println("找到满意的房子");
}
}
```
3. Spring 配置文件
```xml
<beans>
<bean id="landlord" class="com.example.Landlord">
<constructor-arg value="房东张三"/>
</bean>
<bean id="agent" class="com.example.Agent"/>
<bean id="agentProxy" class="com.example.AgentProxy">
<property name="agent" ref="agent"/>
</bean>
<aop:config>
<aop:pointcut id="rentHouse" expression="execution(* com.example.Agent.rentHouse())"/>
<aop:advisor advice-ref="agentProxy" pointcut-ref="rentHouse"/>
</aop:config>
</beans>
```
4. AgentProxy 类
```java
public class AgentProxy implements MethodBeforeAdvice, AfterReturningAdvice {
private Agent agent;
public void setAgent(Agent agent) {
this.agent = agent;
}
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println("中介开始租房");
agent.signContract();
}
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("租房成功");
}
}
```
5. 测试类
```java
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
Landlord landlord = (Landlord) context.getBean("landlord");
landlord.house();
Agent agent = (Agent) context.getBean("agent");
agent.rentHouse();
}
}
```
运行结果:
```
房东张三正在出租房子
中介开始租房
签订租房合同
租房成功
找到满意的房子
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)