这篇文章主要介绍了详解Spring加载Properties配置文件的几种方式:
在项目中使用中很多配置需要每台服务单独配置,比如dubbo框架,dubbo的端口需要在程序中定义。 目前在集群化部署的时候,一台服务器需要部署多个tomcat实例,这种情况下,没发公用一套war包。此时的集群化部署,只能是war包解压 ,拷贝N份 ,对每一份单独修改dubbo监听端口,极大的增加了运维压力,还容易出错。并且在git管理中,每个开发人员需要单独配置自己服务地址,版本控制也比较混乱。因此在方式一与四中,提供了加载本地文件的方式,至于方式二与三是否可以实现,并没有测试,有兴趣的同学可以试试。
一、通过 context:property-placeholder 标签实现配置文件加载
1、用法示例: 在spring.xml配置文件中添加标签
1)项目内配置方式,代码如下:
<context:property-placeholder ignore-unresolvable="true" location="classpath:config/redis-key.properties"/>
2)本地配置方式,代码如下:
<context:property-placeholder ignore-unresolvable="true" location="file:C:\\Users\\Administrator\\Desktop\\db.properties" />
2、在 spring.xml 中使用配置文件属性:
<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
3、在java文件中使用:
@Value("${jdbc_url}")
priivate String jdbcUrl; // 注意:这里变量不能定义成static
二、通过 util:properties 标签实现配置文件加载
1、用法示例: 在spring.xml配置文件中添加标签
代码如下:
<util:properties id="util_Spring" local-override="true" location="classpath:jeesite.properties"/>
2、在spring.xml 中使用配置文件属性:
<property name="username" value="#{util_Spring['jdbc.username']}" />
<property name="password" value="#{util_Spring['jdbc.password']}" />
3、在java文件中使用:
@Value(value="#{util_Spring['UTIL_SERVICE_ONE']}")
private String UTIL_SERVICE_ONE;
三、通过 @PropertySource 注解实现配置文件加载
1、用法示例:在java类文件中使用 PropertySource 注解:
@PropertySource(value={"classpath:redis-key.properties"})
public class ReadProperties {
@Value(value="${jdbc.username}")
private String USER_NAME;
}
2、在java文件中使用:
@Value(value="${jdbc.username}")
private String USER_NAME;
四、通过 PropertyPlaceholderConfigurer 类读取配置文件
1、读取单个本地文件到xml中,用法示例:在 spring.xml 中使用 <bean>标签进行配置
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>file:/opt/config/config1.properties</value>
</property>
</bean>
2、读取多个本地文件到xml中,多个使用locations
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>file:/opt/config/config1.properties</value>
<value>file:/opt/config/config2.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
3、如果读取项目内配置文件,则替换value值为这种方式
<value>classpath:config/redis-key.properties</value>