程序中需要一些常量,但可能因为突变情况而得去改变这些常量,如果在程序中写死的话,难免会很不方便,没有灵活性。
这样就想起了以前写算法题时用程序读文件,改文件总比改程序好吧。。
Spring通过配置可以读取2种格式的配置文件,xml和properties文件。
1、读XML文件
首先你得有一个需要读取变量对应的javaBean
然后自制一个XML配置文件,里面放入需要读取的值,形式如下:
使用有两种方法:
a.利用ClassPathXmlApplicationContext
b.利用FileSystemResource读取
2、读Properties文件
还用上面的Test类
自制xxx.properties文件
利用org.springframework.beans.factory.support.PropertiesBeanDefinitionReader来读取属性文件
当然也可以直接用JAVA文件操作来读取.
这样就想起了以前写算法题时用程序读文件,改文件总比改程序好吧。。
Spring通过配置可以读取2种格式的配置文件,xml和properties文件。
1、读XML文件
首先你得有一个需要读取变量对应的javaBean
public class Test
{
private int var;
//setter和getter
//...
}
在spring中配置这个javaBean,id为test.
然后自制一个XML配置文件,里面放入需要读取的值,形式如下:
<xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="test" class="Test类的路径">
<property name="var">
<value>20</value>
</property>
</bean>
</beans>
使用有两种方法:
a.利用ClassPathXmlApplicationContext
ApplicationContext context = new ClassPathXmlApplicationContext("xxx.xml");
Test test = (Test)context.getBean("test");
System.out.println(test.getVar());
b.利用FileSystemResource读取
Resource rs = new FileSystemResource("xxx.xml文件的路径");
BeanFactory factory = new XmlBeanFactory(rs);
Test test = (Test)factory.getBean("test");\
System.out.println(test.getVar());
2、读Properties文件
还用上面的Test类
自制xxx.properties文件
test.class=package.Test //package为Test的包地址,test为Test对应的javaBean
test.var=10
利用org.springframework.beans.factory.support.PropertiesBeanDefinitionReader来读取属性文件
BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(reg);
reader.loadBeanDefinitions(new ClassPathResource("xxx.properties"));
BeanFactory factory = (BeanFactory)reg;
Test test = (Test)factory.getBean("test");
System.out.println(test.getVar());
当然也可以直接用JAVA文件操作来读取.