Switch between two beans in spring
I have two beans which comes from the same class(id1 and id2), the difference is ids and some properties. In the code, I called getbean(id1) to get the object.
开发者_运维百科How can I switch to id2 without recompiling the code?
If you have two different beans wit different properties that means you have two different objects. That means you treat them as you would normally treat different objects -
BeanClass b1 = (BeanClass) ctx.getBean("id1");
BeanClass b2 = (BeanClass) ctx.getBean("id2");
However if you have a seperate scenerio where you load bean 1 in your class for normal working and bean 2 in your class when you run it via JUnit then you should have a different approach altogether -
Have two different applicationContext.xml files. First one loads when your code runs and then other(applicationContext-test.xml) is loaded when you are running your code via JUNIT. This way you can load different beans without changing the code.
It doesn't seems good design,
Spring are generally service beans, you should have only one implementation object of Bean.
well then also if you want to do it.
then read the bean ID from Properties
file while fetching bean.
From your question, I'm assuming that you want to switch between bean instances programatically....
Given the following setup:
<bean id="instance1" class="my.bean.A">
<property name="property_B">
<ref local="B"/>
</property>
</bean>
<bean id="instance2" class="my.bean.A">
<property name="property_B">
<ref local="B"/>
</property>
</bean>
then in your code, you can switch between the two using the ApplicationContext... (This is Spring 2.x code)
ApplicationContext ctx = new FileSystemXmlApplicationContext(
"my-XML-Config-File-Above.xml");
A instance1 = (A) ctx.getBean("instance1");
A instance2 = (A) ctx.getBean("instance2");
精彩评论