[英]How do I inject property from one bean into another in Spring 3.0?
在Spring 3.0.2中,我試圖將Bean A的屬性注入另一個Bean B,但是Spring EL無效。
Bean A是用Java手動創建的。 Bean B是通過XML創建的。
在這種情況下, 豆A是馬鈴薯 , 豆B是嬰兒 (兩者都包裝在springinit中)。
豆A(馬鈴薯):
public class Potato {
String potatoType;
public String getPotatoType() { return potatoType; }
public void setPotatoType(String potatoType) { this.potatoType = potatoType; }
@Override
public String toString() {
return "Potato{" + "potatoType=" + potatoType + '}';
}
}
豆B(寶貝):
public class Baby {
private String name;
private Potato potatoThing;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Potato getPotatoThing() { return potatoThing; }
public void setPotatoThing(Potato p) { this.potatoThing = p; }
@Override
public String toString() {
return "Baby{" + "name=" + name +
", potatoThing=" + potatoThing + '}';
}
}
在我的Main類中,我創建了一個Potato,並在嘗試制作Baby時在XML中使用它
package springinit;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.ClassPathResource;
public class Main {
public static void main(String[] args) {
GenericApplicationContext ctx= new GenericApplicationContext();
// define java-based spring bean
ctx.registerBeanDefinition("myPotato",
genericBeanDefinition(Potato.class)
.addPropertyValue("potatoType", "spudzz")
.getBeanDefinition());
// read in XML-bean
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
xmlReader.loadBeanDefinitions(
new ClassPathResource("/resources/spring_init.xml"));
// print out results
System.out.format(
"Baby: %s%n%n" +
"Potato: %s%n",
ctx.getBean(Baby.class),
ctx.getBean(Potato.class)
);
}
}
這是我的spring_init.xml:
<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-3.0.xsd">
<bean id="myBaby" class="springinit.Baby" depends-on="myPotato">
<property name="name" value="#{myPotato.potatoType}" />
<property name="potatoThing">
<ref bean="myPotato" />
</property>
</bean>
</beans>
當我運行main時,我得到這個輸出:
Baby: Baby{name=#{myPotato.potatoType}, potatoThing=Potato{potatoType=spudzz}}
Potato: Potato{potatoType=spudzz}
我希望寶寶的名字是“spudzz”,這是myPotato的財產。 為什么不春天將這個值注入嬰兒?
謝謝你的閱讀。 我希望它足夠清楚。
也許你需要在獲取bean之前調用ctx.refresh()
。
來自javadoc :
典型用法是通過BeanDefinitionRegistry接口注冊各種bean定義,然后調用AbstractApplicationContext.refresh()以使用應用程序上下文語義初始化這些bean(處理ApplicationContextAware,自動檢測BeanFactoryPostProcessors等)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.