spring读取properties配置文件
可以通过以下方式读取配置文件,使用BeanDefinitionRegisttry,PropertiesBeanDefinitionReader类读取配置文件
BeanDefinitionRegistry reg=new DefaultListableBeanFactory();
PropertiesBeanDefinitionReader reader=new PropertiesBeanDefinitionReader(reg);
reader.loadBeanDefinitions(new ClassPathResource("beans-config.properties"));
//读取properties的值
BeanFactory factory=(BeanFactory)reg;
//beanFactory工厂
HelloBean hello=(HelloBean)factory.getBean("helloBean"); //获取bean
System.out.println(hello.getHelloWord());
文件的位置如下所示:
在程序中编写,定义程序与程序之间的依赖关系
MutablePropertyValues properties=new MutablePropertyValues();
properties.addPropertyValue("helloWord","hello!Justry!!!!!");
RootBeanDefinition definition=new RootBeanDefinition(HelloBean.class,null,properties);
BeanDefinitionRegistry reg1=new DefaultListableBeanFactory();
reg1.registerBeanDefinition("helloBean",definition);
BeanFactory factory1=(BeanFactory)reg1;
HelloBean hello1=(HelloBean)factory1.getBean("helloBean");
System.out.println(hello1.getHelloWord());