在春季启动时无法读取环境属性

时间:2017-03-30 08:48:05

标签: java spring spring-boot environment-variables

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

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启动应用程序相同的应用程序,则它不会读取环境属性,因此返回值为null。

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

2 个答案:

答案 0 :(得分:0)

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);
    }

答案 1 :(得分:0)

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;
        }

    }
}