• Spring —— <context:property-placeholder/>元素


    外在化应用参数的配置

    在开发企业应用期间,或者在将企业应用部署到生产环境时,应用依赖的很多参数信息往往需要调整,比如LDAP连接、RDBMS JDBC连接信息。对这类信息进行外在化管理显得格外重要。PropertyPlaceholderConfigurer和PropertyOverrideConfigurer对象,它们正是担负着外在化配置应用参数的重任。

    <context:property-placeholder/>元素

    PropertyPlaceholderConfigurer实现了BeanFactoryPostProcessor接口,它能够对<bean/>中的属性值进行外在化管理。开发者可以提供单独的属性文件来管理相关属性。比如,存在如下属性文件,摘自userinfo.properties。

    db.username=scott
    db.password=tiger

    如下内容摘自propertyplaceholderconfigurer.xml。正常情况下,在userInfo的定义中不会出现${db.username}、${db.password}等类似信息,这里采用PropertyPlaceholderConfigurer管理username和password属性的取值。DI容器实例化userInfo前,PropertyPlaceholderConfigurer会修改userInfo的元数据信息(<bean/>定义),它会用userinfo.properties中db.username对应的scott值替换${db.username}、db.password对应的tiger值替换${db.password}。最终,DI容器在实例化userInfo时,UserInfo便会得到新的属性值,而不是${db.username}、${db.password}等类似信息。

    <bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>userinfo.properties</value>
            </list>
        </property>
    </bean>
    <bean name="userInfo" class="test.UserInfo">
        <property name="username" value="${db.username}"/>
        <property name="password" value="${db.password}"/>
    </bean>

    通过运行并分析PropertyPlaceholderConfigurerDemo示例应用,开发者能够深入理解PropertyPlaceholderConfigurer。为简化PropertyPlaceholderConfigurer的使用,Spring提供了<context:property-placeholder/>元素。下面给出了配置示例,启用它后,开发者便不用配置PropertyPlaceholderConfigurer对象了。

    <context:property-placeholder location="userinfo.properties"/>

    PropertyPlaceholderConfigurer内置的功能非常丰富,如果它未找到${xxx}中定义的xxx键,它还会去JVM系统属性(System.getProperty())和环境变量(System.getenv())中寻找。通过启用systemPropertiesMode和searchSystemEnvironment属性,开发者能够控制这一行为。

  • 相关阅读:
    在Vue构建的SPA网页里 刷新的话,显示404页面
    springboot2.x 设置404页面
    关于Typora不显示PicGo.app的问题
    DBeaver中table插入新的数据
    DBeaver修改table的column名字
    Zeal
    Android Studio 快速创建 Toast
    使用VSCode调试单个JavaScript文件
    使用maven打包普通的java项目
    在命令行界面实现彩色字符输出 -- 并且介绍和这个相关的比较好用的java类库
  • 原文地址:https://www.cnblogs.com/yifanSJ/p/9226900.html
Copyright © 2020-2023  润新知