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

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