在xml模式下的Bean加载篇章中我们看到容器AbstractRefreshableApplicationContext在方法loadBeanDefinitions中加载我们的beanDefinition,在子类AbstractXmlApplicationContext继承该方法loadBeanDefinitions(DefaultListableBeanFactory) ,指定XmlBeanDefinitionReader进行加载。
/**
* Load bean definitions into the given bean factory, typically through
* delegating to one or more bean definition readers.
* @param beanFactory the bean factory to load bean definitions into
* @throws BeansException if parsing of the bean definitions failed
* @throws IOException if loading of bean definition files failed
* @see org.springframework.beans.factory.support.PropertiesBeanDefinitionReader
* @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
*/
protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
throws BeansException, IOException;
也就是说如果我们需要以property形式加载的话,只要指定PropertiesBeanDefinitionReader进行阅读就行了,该reader不详解,我们这里看一个案例就行了。
案例:
定义一个property文件,property_parse_demo.property:
people.(class)=com.jack.ascp.purchase.app.test.spring.parse.People
people.name=jpl
people.gender=man
public class People {
private String name;
private String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
代码:
public static void main(String[] args) {
GenericApplicationContext context = new GenericApplicationContext();
BeanDefinitionRegistry beanDefinitionRegistry = (BeanDefinitionRegistry)context.getBeanFactory();
PropertiesBeanDefinitionReader propertiesBeanDefinitionReader = new PropertiesBeanDefinitionReader(beanDefinitionRegistry);
// 设置ResourceLoader为GenericApplicationContext
propertiesBeanDefinitionReader.setResourceLoader(context);
propertiesBeanDefinitionReader.loadBeanDefinitions("property_parse_demo.property");
// GenericApplicationContext的刷新不在构造函数,手动刷新
context.refresh();
People people = context.getBean(People.class);
System.out.println(people.getGender());
System.out.println(people.getName());
}
}
我们需要在容器创建之后指定reader,但是AbstractRefreshableApplicationContext
容器的刷新是在构造函数之中完成,因此我们使用GenericApplicationContext (通用容器)进行测试,并且在指定reader之后手动刷新容器。