美文网首页
spring从环境变量获取配置项

spring从环境变量获取配置项

作者: 炫迈哥 | 来源:发表于2017-11-06 17:23 被阅读0次

方式一,实现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;
    }

    /**
     * 从环境变量中获取配置项值
     */
    @Override
    public void setEnvironment(Environment environment) {
        this.cornerstoneDomain = environment.getProperty("BUC_DOMAIN", "xxx");
        this.staragentHome = environment.getProperty("AGENT-HOME", "xxx");
    }
}
  • 好处:环境变量里没有时可以自己指定默认值,spring启动不会报错
  • 缺点:如果你的数据库地址,账号等也从env注入,spring的xml配置里没法这样读取

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

查看org.springframework.beans.factory.config.PropertyPlaceholderConfigurer源码,发现有个神奇的字段:

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

相关文章

网友评论

      本文标题:spring从环境变量获取配置项

      本文链接:https://www.haomeiwen.com/subject/doglmxtx.html