我爱熊猫

最新评论

spring aop 之三利用aop实现bean注入的热插拔

利用spring可以实现bean注入的热插拔。

先看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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="helloServiceTarget" class="cn.com.ultrapower.service.HelloServiceImpl"/>
<bean id="welcomeServiceTarget" class="cn.com.ultrapower.service.WelcomeServiceImpl"/>
<bean id="swapper" class="org.springframework.aop.target.HotSwappableTargetSource">
<constructor-arg ref="helloServiceTarget"/>
</bean>
<bean id="helloService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="targetSource" ref="swapper"/>
</bean>
</beans>

上面代码中HelloServiceImpl会打印hello,WelcomeServiceImpl会打印welcome。

helloService默认会注入的是helloServiceTarget,利用swapper bean 在程序运行时将注入引用的修改为welcomeServiceTarget。

测试用例如下:

public void testSwapper() {
/*
* 实现了动态将helloservice实现切换到welcomeservice实现
*/
String[] paths = {"applicationContext-hotswapper.xml"};
ApplicationContext context = new ClassPathXmlApplicationContext(paths);
HotSwappableTargetSource swapper = (HotSwappableTargetSource) context.getBean("swapper");
IHelloService service = (IHelloService) context.getBean("helloService");
// 第一次输出
service.sayHello();
//获取Welcome实现
WelcomeServiceImpl welcomeTarget = (WelcomeServiceImpl) context.getBean("welcomeServiceTarget");
//切换为welcome实现
swapper.swap(welcomeTarget);
// 第二次输出
service.sayHello();
}

上面代码会输出:

hello

welcome

验证了程序在运行中将service的实现由helloserviceImpl切换到welcomeserviceimpl

posted on 2008-06-07 20:56 flyoo 阅读(2612) 评论(1)  编辑  收藏

评论

# re: spring aop 之三利用aop实现bean注入的热插拔[未登录] 2013-12-16 15:25

你上面说了等于白说。来点干货,哥们!  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
博客园   IT新闻   Chat2DB   C++博客   博问