在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 + '}';
}
}
Run Code Online (Sandbox Code Playgroud)
豆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 + '}';
}
}
Run Code Online (Sandbox Code Playgroud)
在我的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)
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的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>
Run Code Online (Sandbox Code Playgroud)
当我运行main时,我得到这个输出:
Baby: Baby{name=#{myPotato.potatoType}, potatoThing=Potato{potatoType=spudzz}}
Potato: Potato{potatoType=spudzz}
Run Code Online (Sandbox Code Playgroud)
我希望宝宝的名字是"spudzz",这是myPotato的财产.为什么不春天将这个值注入婴儿?
谢谢你的阅读.我希望它足够清楚.
| 归档时间: |
|
| 查看次数: |
3314 次 |
| 最近记录: |