chapter2:
package com.apress.prospring.ch2;
import java.io.FileInputStream;
import java.util.Properties;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
public class HelloWorldWithDI {
public static void main(String[] args) throws Exception {
//get BeanFactory
BeanFactory factory=getBeanFactory();
MessageRenderer mr=(MessageRenderer)factory.getBean("renderer");
mr.render();
}
private static BeanFactory getBeanFactory() throws Exception {
// get the bean factory
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
// create a definition reader
PropertiesBeanDefinitionReader rdr = new PropertiesBeanDefinitionReader(
factory);
// load the configuration options
Properties props = new Properties();
props.load(new FileInputStream("./ch2/src/conf/beans.properties"));
rdr.registerBeanDefinitions(props);
return factory;
}
}
beans.properties:
renderer.class=com.apress.prospring.ch2.StandardOutMessageRenderer
renderer.messageProvider(ref)=provider
provider.class=com.apress.prospring.ch2.HelloWorldMessageProvider
DefaultListableBeanFactory负责从properties文件读取BeanFactory的配置信息,然后返回已配置的实例。
这个配置文件已经定义了DI关系,所以在main方法中无需设置MessageRenderer 和MessageProvider的依赖关系。