【问题标题】:Environment properties not getting read in spring boot在 Spring Boot 中未读取环境属性
【发布时间】:2017-03-30 08:48:05
【问题描述】:

我有一个实用程序类来读取环境变量。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public final class PropertyUtil {

    /** The system environment. */
    private static Environment environment;

    public static String getConfigProp(final String key) {
        return environment.getProperty(key);
    }

    @Autowired
    public void setEnvironment(Environment environment) {
        PropertyUtil.environment = environment;
    }
}

我在初始化时在一个 bean 中使用它。问题是,如果我在 tomcat 上部署 war 文件,它会运行文件,但如果我从 eclipse 运行与 spring boot 应用程序相同的应用程序,它不会读取环境属性,因此返回值为 null。

知道导致这个问题的原因是什么吗?

【问题讨论】:

标签: java spring spring-boot environment-variables


【解决方案1】:
package com.myspringboot.controller;

import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public  class PropertyUtil  implements EnvironmentAware {

    /** The system environment. */
    public  Environment environment;

    public  String getConfigProp(String key) {
        return environment.getProperty(key);
    }
    @Override
    public void setEnvironment(Environment arg0) {
        environment=arg0;

    }
}
    @Test
    public void testProperty(){
/*      String driver= System.getenv().get("spring.datasource.driverClassName");
        System.out.println(driver);
        System.out.println(PropertyUtil.environment);*/
        String str= propertyUtil.getConfigProp("spring.datasource.driverClassName");
        System.out.println(str);
    }

【讨论】:

    【解决方案2】:
    package com.myspringboot.controller;
    
    import org.springframework.context.EnvironmentAware;
    import org.springframework.core.env.Environment;
    import org.springframework.stereotype.Component;
    @Component
    public final  class PropertyUtil  implements EnvironmentAware {
    
        /** The system environment. */
        public static  Environment environment;
    
        public static  String getConfigProp(String key) {
            return environment.getProperty(key);
        }
        @Override
        public void setEnvironment(Environment arg0) {
            if(environment==null){
                environment=arg0;
            }
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-15
      • 2019-09-18
      • 1970-01-01
      • 2021-03-12
      • 2017-12-01
      • 2018-08-08
      • 2020-05-05
      • 2020-01-18
      • 2016-04-29
      相关资源
      最近更新 更多