还是用上次的生产者——消费者例子,代码如下:
package my.spring.bean.demo;
public interface IoCImpl {
public void run();
}
package my.spring.bean.demo;
import my.spring.bean.pojo.Dispatcher;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
public class PropertyFileImpl implements IoCImpl {
@Override
public void run() {
// TODO Auto-generated method stub
DefaultListableBeanFactory registry=new DefaultListableBeanFactory();
BeanFactory container=bindViaPropertyFile(registry);
Dispatcher dispatcher=(Dispatcher)container.getBean("dispatcherB");
dispatcher.dispatch();
}
public static BeanFactory bindViaPropertyFile(BeanDefinitionRegistry registry){
PropertiesBeanDefinitionReader reader=new PropertiesBeanDefinitionReader(registry);
reader.loadBeanDefinitions(ClassLoader.getSystemResource("")+"../binding-config.properties");
return (BeanFactory) registry;
}
}
注意properties文件的目录,这里采用ClassLoader获取当前的classpath。
properties文件配置如下,其中包含了“constructor注入”和“setter注入”两种方式
dispatcherB.(class)=my.spring.bean.pojo.Dispatcher
#Introject via constructor
dispatcherB.$0(ref)=producerB
dispatcherB.$1(ref)=consumerB
#Introject by setting properties
#dispatcherB.producer(ref)=producerB
#dispatcherB.consumer(ref)=consumerB
producerB.(class)=my.spring.bean.pojo.Producer
producerB.$0=106
consumerB.(class)=my.spring.bean.pojo.Consumer
consumerB.$0=88
具体语法参照SpringAPI中PropertiesBeanDefinitionReader示例说明,当然也可以自己重写语义规则
最后单元测试
package my.spring.bean.demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class IoCImplTest {
private static IoCImpl impl=null;
@Test
public void testPropertyFileImpl(){
impl=new PropertyFileImpl();
impl.run();
}
}
这里要对核心类PropertiesBeanDefinitionReader稍作讲解,先看下各个类之间的关系