properties配置文件的读取
现在的项目为了更易维护,一般都是使用配置文件。这样做更灵活,可以很方便应对不同的环境。properties文件大家也见得多了,下面介绍一下properties的读取问题
一、普通类加载:
public FileSkServer() {
Properties pro = new Properties();
pro.load(FileSkServer.class.getResourceAsStream("configure.properties"));//在跟类同一个目录里面的文件
String port = pro.getProperty("fileServer.port");//配置文件里的字段
}
使用pro.getProperty(“fileServer.port”);就可以获取fileServer.port的值了
二、spring MVC Controller加载方式:
1、首先在applicationContext.xml配置
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations" >
<list>
<value>classpath:config/configure.properties</value>
</list>
</property>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties" />
</bean>
configure.properties是你的文件名,config是配置文件所在的目录,
结构 ![Image 1][]
然后在Controller里中使用注解获得配置项内容:
@Value("#{configProperties['server.file.path']}")
private String filePath;
public void setFilePath(String filePath) {
this.filePath = filePath;
}
这样就可以直接获取配置项server.file.path了
-—————————————————-20160510添加——————————————————
三、通过ResourceBundle来加载
示例代码:
ResourceBundle bundle=ResourceBundle.getBundle("config");
String driver=bundle.getString("driver");
创建一个默认的ResourceBundle对象
ResourceBundle会查找WEB-INF\classes\下的config.properties的文件
它跟普通java类的命名规则完全一样:
- 区分大小写
- 扩展名 .properties 省略。就像对于类可以省略掉 .class扩展名一样
- 资源文件必须位于指定包的路径之下(位于所指定的classpath中)
假如你是在非Web项目中使用,则一定要写资源文件的路径,也就是包路径必须存在。
如果是Web项目,不写包路径可以,此时将资源文件放在WEB-INF\classes\目录下就可以。
然后可以直接获取值,这里也是区分大小写的,大家注意
-——————————————————-20170626添加———————————————————
四、通过spring框架来读取
try {
config = PropertiesLoaderUtils.loadProperties(new EncodedResource(new ClassPathResource("configure.properties"), Consts.UTF_8));
} catch (Exception e) {
e.printStackTrace();
}
查找WEB-INF\classes\下的config.properties的文件,也可以放到其他目录。
[Image 1]:
还没有评论,来说两句吧...