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

方式一,實現(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)境變量中獲取配置項值
     */
    @Override
    public void setEnvironment(Environment environment) {
        this.cornerstoneDomain = environment.getProperty("BUC_DOMAIN", "xxx");
        this.staragentHome = environment.getProperty("AGENT-HOME", "xxx");
    }
}
  • 好處:環(huán)境變量里沒有時可以自己指定默認值,spring啟動不會報錯
  • 缺點:如果你的數(shù)據(jù)庫地址,賬號等也從env注入,spring的xml配置里沒法這樣讀取

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

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

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);
                        // 哈哈哈哈哈,我喜歡這個
            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;
        }
    }


呵呵噠,他有自己設定默認值,不用管,反正我直接用setter注入一個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}")的形式注入啦(不過注意哦,不存在的話spring會直接啟動報錯的喲)
  • xml里面也可以直接引。。

mark

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

相關閱讀更多精彩內容

友情鏈接更多精彩內容