package eg;
public class ExampleBean {
private AnotherBean beanOne;
private YetAnotherBean beanTwo;
public AnotherBean getBeanOne() {
return beanOne;
}
public void setBeanOne(AnotherBean beanOne) {
this.beanOne = beanOne;
}
public YetAnotherBean getBeanTwo() {
return beanTwo;
}
public void setBeanTwo(YetAnotherBean beanTwo) {
this.beanTwo = beanTwo;
}
}
package eg;
import java.awt.Color;
import java.util.Locale;
public class AnotherBean {
private Color color;
private Locale locale;
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public Locale getLocale() {
return locale;
}
public void setLocale(Locale locale) {
this.locale = locale;
}
}
package eg;
import java.util.Properties;
public class YetAnotherBean {
private Properties properties;
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
}
上面的代码中,我们看出ExampleBean引用了AnotherBean和YetAnotherBean, 这里就牵扯到什么时候将AnotherBean和YetAnotherBean和ExampleBean的关系建立起来,在spring中通过配置文件, 由spring的容器自己注入关系,如下:
配置文件kissesmlBeanFactory.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="exampleBean" class="eg.ExampleBean">
<property name="beanOne">
<ref bean="anotherExampleBean"/>
</property>
<property name="beanTwo">
<ref bean="yetAnotherBean"/>
</property>
</bean>
<beans>
那么我们如何得到ExampleBean或者其他的Bean实例呢?
public class XmlBeanFactoryEx {
public static void main(String[] args) {
try{
InputStream is = new FileInputStream(new File("XmlBeanFactory.xml"));
BeanFactory beanFactory = new XmlBeanFactory(is);
ExampleBean ebOne = (ExampleBean)beanFactory.getBean("exampleBean");
ExampleBean ebTwo = (ExampleBean)
System.out.println(ebOne);
}catch(Exception e){
e.printStackTrace();
}
}
}