房东租房的例子
有一个房东要出租房屋:
package com.shin.demo04;
public class Host implements Rent {
public void rent() {
System.out.println("房东出租房屋");
}
}
package com.shin.demo04;
public interface Rent {
void rent();
}
在动态代理的例子中,已经可以实现通过一个代理生成类给各种各样的被代理类动态生成代理类了。但是从租房者的角度来看操作还是略复杂,不够透明。下面用SpringAOP来实现,先写个扩展功能类:
package com.shin.demo04;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class Action implements MethodBeforeAdvice {
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println("带你看房");
}
}
然后写applicationContext.xml来配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<context:annotation-config/>
<bean id="host" class="com.shin.demo04.Host"/>
<bean id="action" class="com.shin.demo04.Action"/>
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.shin.demo04.Host.*(..))"/>
<aop:advisor advice-ref="action" pointcut-ref="pointcut"></aop:advisor>
</aop:config>
</beans>
关于SpingAOP的概念和配置就不介绍了,这里的配置作用就是把action下的操作切入被代理类。具体切在哪里看Action实现了哪个接口。这里还要注意下execution表达式的语法。
有一个打工人前来租房:
package com.shin.demo04;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Rent host = context.getBean("host",Rent.class);
host.rent();
}
}
这时打工人不需要自己new任何对象了,从容器中拿个房东就可以租房了,从打工人的角度也看不到中介了。运行结果:

分析
- 跟动态代理的区别在哪?首先房东这个对象交给Spring来管理了,然后如果我们为房东配置了切面,那么Spring在创建房东的时候,实际上创建的是房东的代理对象。这也就是Rent host = context.getBean(“host”,Rent.class);中写的不是Host.class的原因。
- 几个要素:
- 被代理的类
- 被代理的类实现的接口
- 切面类
- spring配置bean和切面
- 调用者
本文介绍使用Spring AOP实现租房业务场景的具体步骤,包括定义房东类、扩展功能类及配置文件等内容,使租房过程更加透明高效。
541

被折叠的 条评论
为什么被折叠?



