spring從環(huán)境變量獲取配置項(xiàng)

方式一,實(shí)現(xiàn)EnvironmentAware接口

例子:

public class CornerstoneConfiguration implements EnvironmentAware {

    private String cornerstoneDomain;

    private String staragentHome;

    public final String getStaragentHome() {
        return staragentHome;
    }

    public final void setStaragentHome(String staragentHome) {
        this.staragentHome = staragentHome;
    }

    public final String getCornerstoneDomain() {
        return cornerstoneDomain;
    }

    public final void setCornerstoneDomain(String cornerstoneDomain) {
        this.cornerstoneDomain = cornerstoneDomain;
    }

    /**
     * 從環(huán)境變量中獲取配置項(xiàng)值
     */
    @Override
    public void setEnvironment(Environment environment) {
        this.cornerstoneDomain = environment.getProperty("BUC_DOMAIN", "xxx");
        this.staragentHome = environment.getProperty("AGENT-HOME", "xxx");
    }
}
  • 好處:環(huán)境變量里沒(méi)有時(shí)可以自己指定默認(rèn)值,spring啟動(dòng)不會(huì)報(bào)錯(cuò)
  • 缺點(diǎn):如果你的數(shù)據(jù)庫(kù)地址,賬號(hào)等也從env注入,spring的xml配置里沒(méi)法這樣讀取

方式二:借助org.springframework.beans.factory.config.PropertyPlaceholderConfigurer

查看org.springframework.beans.factory.config.PropertyPlaceholderConfigurer源碼,發(fā)現(xiàn)有個(gè)神奇的字段:

private boolean searchSystemEnvironment =
            !SpringProperties.getFlag(AbstractEnvironment.IGNORE_GETENV_PROPERTY_NAME);


    /**
     * Set whether to search for a matching system environment variable
     * if no matching system property has been found. Only applied when
     * "systemPropertyMode" is active (i.e. "fallback" or "override"), right
     * after checking JVM system properties.
     * <p>Default is "true". Switch this setting off to never resolve placeholders
     * against system environment variables. Note that it is generally recommended
     * to pass external values in as JVM system properties: This can easily be
     * achieved in a startup script, even for existing environment variables.
     * <p><b>NOTE:</b> Access to environment variables does not work on the
     * Sun VM 1.4, where the corresponding {@link System#getenv} support was
     * disabled - before it eventually got re-enabled for the Sun VM 1.5.
     * Please upgrade to 1.5 (or higher) if you intend to rely on the
     * environment variable support.
     * @see #setSystemPropertiesMode
     * @see java.lang.System#getProperty(String)
     * @see java.lang.System#getenv(String)
     */
    public void setSearchSystemEnvironment(boolean searchSystemEnvironment) {
        this.searchSystemEnvironment = searchSystemEnvironment;
    }

protected String resolveSystemProperty(String key) {
        try {
            String value = System.getProperty(key);
                        // 哈哈哈哈哈,我喜歡這個(gè)
            if (value == null && this.searchSystemEnvironment) {
                value = System.getenv(key);
            }
            return value;
        }
        catch (Throwable ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not access system property '" + key + "': " + ex);
            }
            return null;
        }
    }


呵呵噠,他有自己設(shè)定默認(rèn)值,不用管,反正我直接用setter注入一個(gè)true給它,哇嘎嘎。。。

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:app-config.properties</value>
                <value>classpath:application.properties</value>
            </list>
        </property>
        <property name="searchSystemEnvironment" value="true" />
    </bean>

  • 這樣之后,在spring的任何bean里面都可以@Value("${xxx}")的形式注入啦(不過(guò)注意哦,不存在的話spring會(huì)直接啟動(dòng)報(bào)錯(cuò)的喲)
  • xml里面也可以直接引。。

mark

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容