Spring读取properties文件

property-placeholder标签

<context:property-placeholder location="classpath:system-params-dev.properties" />

相当于

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations" value="classpath:system-params-dev.properties"/>
</bean>

这样就再Spring配置文件中使用 ${property-name} 了,好处就是我们可以自定义一些系统环境变量,避免直接修改xml配置带来的复杂度和风险。

<bean id="dataSource" destroy-method="close"
        class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

通过Spring在Java中读取properties的值

PropertyPlaceholderConfigurer并无法做到,只能使用PropertiesFactoryBean来实现
PropertiesFactoryBean会出初始化一个Property对象来存储值

<bean id="propertiesFactoryBean" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 
    <property name="location" value="classpath:system-params-dev.properties"/> 
</bean>
@Component
public class SystemParams {

    @Autowired
    PropertiesFactoryBean bean;

    public String getValue(String key) throws IOException {
        Object value = bean.getObject().get(key);
        return value == null ? null : value.toString();
    }
    //带占位符的properties解析
    public String getValue(String key, Object...params) throws IOException {
        return MessageFormat.format(this.getValue(key), params);
    }

}

猜你喜欢

转载自blog.csdn.net/u012557814/article/details/79533088