在Spring 3.0.2中,我試圖將Bean A的屬性注入另一個Bean B,但是Spring EL沒有工作。如何在Spring 3.0中將屬性從一個bean注入另一個?
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 + '}';
}
}
在我的主類,我創建了一個土豆,並試圖讓使用它時,在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>
當我運行主,我得到這樣的輸出:
Baby: Baby{name=#{myPotato.potatoType}, potatoThing=Potato{potatoType=spudzz}}
Potato: Potato{potatoType=spudzz}
我想寶寶的名字是「spudzz」,這是myPotato的屬性。爲什麼春天不會將這個價值注入寶寶?
謝謝您的閱讀。我希望這是很清楚的。
工作正常!感謝您的幫助! 實際上,我想根據命令行參數爲JMX服務器注入端口號,所以我將在加載JMX文件之前調用ctx.refresh()。 – 2010-11-23 16:02:45