Spring 导入资源文件

Spring 有多种方式可以导入资源文件,可以把这些属性文件里的属性值注入到 bean 的属性上。

1. 通过 <context:property-placeholder> 标签导入

通过这种方式导入的所有属性在同一个命名空间下,如果多个属性文件里有相同的属性名,以先导入的属性文件的属性为准,不会出现覆盖。可以通过 @Value("${propName}") 的方式注入到 bean 的属性上。

这种方式不能对属性文件指定 id,没法引用指定属性文件的属性,如果有同名的属性,引用到的总是第一个导入的属性。

配置如下:

<!-- 导入外部的资源文件,可以通过 @Value("${propName}") 的方式注入到 bean 的属性上 。 -->
<context:property-placeholder
    location="classpath:/learn/properties/1.properties"
    ignore-unresolvable="true" />
<!-- 要使用 context:property-placeholder 导入多个资源文件,必须指定 ignore-unresolvable="true" -->
<!-- 多个属性文件中,属性名相同的,以第一个加载的为准,不会出现后面加载的覆盖前面的 -->
<context:property-placeholder location="learn/properties/2.properties"
    ignore-unresolvable="true" />

2. 通过 <util:properties> 标签导入

<util:properties> 标签对应的是一个 java.util.Properties 实例,可以指定 bean 的 id,这样就可以引用某个属性文件的属性,而不管是否有多个属性有同名的属性。

通过这种方式导入的,注入到 bean 的属性上,需要用 Spring 的表达式语言,形如 @Value("#{propertiesBeanId['propName']}")

<!-- 这种加载方式可以在代码中通过 @Value 注解进行注入, 可以将配置整体赋给 Properties 类型的类变量 -->
<!-- <util:properties/> 标签只能加载一个文件,当多个属性文件需要被加载的时候,可以使用多个该标签 -->
<util:properties id="remoteSettings"
    location="classpath:/learn/properties/resources.properties" />

<!-- 配置多个属性文件 -->
<bean id="settings"
    class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
            <value>classpath:/learn/properties/resources.properties</value>
            <value>classpath:/learn/properties/more.properties</value>
            <!-- <value>file:/path/to/properties/file</value> -->
        </list>
    </property>
</bean>

3. 注入属性到 bean 的变量上

对于通过 <util:properties> 标签导入的配置,可以作为一个整体注入到 java.util.Properties 类型的变量上。

public class Resources {
    @Value("#{remoteSettings['upstream.host']}")
    private String host;

    @Value("#{remoteSettings['upstream.port']}")
    private int port;

    @Value("#{remoteSettings}")
    private Properties remoteSettings;

    @Autowired
    @Qualifier("settings")
    private Properties settings;

    @Value("${1_properties_prop1}")
    private String prop1_1;

    @Value("${1_properties_prop2}")
    private String prop1_2;

    @Value("${2_properties_prop2}")
    private String prop2_2;

    public String getProp2_2() {
        return prop2_2;
    }

    public String getProp1_1() {
        return prop1_1;
    }

    public String getProp1_2() {
        return prop1_2;
    }

    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }

    public String getPropValue(String propName) {
        return remoteSettings.getProperty(propName);
    }

    public String getMorePropValue(String propName) {
        return settings.getProperty(propName);
    }
}

欢迎关注我的微信公众号: coderbee笔记,可以更及时回复你的讨论。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据