Spring的屬性注入(SPEL)

Spring的屬性注入(SPEL)

介紹

在開發中有時候有些參數我們並不想直接寫成硬編碼形式,我們更想寫成配置文件形式,使其更加靈活。

Spring提供了PropertyPlaceholderConfigurer類和SPEL表達式能夠很好的滿足我們的需求。

SPEL讀取配置文件應用

使用bean配置PropertyPlaceholderConfigurer

<!-- 配置PropertyPlaceholderConfigurer -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:config/db.properties</value>
            <value>classpath:config/user.properties</value>
        </list>
    </property>
</bean>

1、在配置文件中讀取
<!-- 讀取配置文件值 -->
<bean id="db" class="com.xuyi.hellospring.scan.DB">
    <property name="username" value="${db.username}"></property>
    <property name="password" value="${db.password}"></property>
</bean>


2、在Java代碼中通過註解讀取

public class User
{

    @Value(value = "${user.name}")
    private String name;
    @Value(value = "${user.age}")
    private int age;

}

使用context:property-placeholder配置

<!-- 配置context:property-placeholder -->
<context:property-placeholder
    location="classpath:config/db.properties,classpath:config/user.properties" />

備註:支持ant風格通配符
<context:property-placeholder
    location="classpath:config/*.properties" />


讀取配置文件值和上面一樣

總結

Spring提供PropertyPlaceholderConfigurer和SPEL讀取配置文件,能夠使應用解耦和更加靈活。配合高級特性profile更叼哦。

參考

1、http://docs.spring.io/spring/docs/4.2.7.RELEASE/spring-framework-reference/htmlsingle/#beans-factory-extension-factory-postprocessors

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章