【问题标题】:Spring boot - Get enviromental variableSpring Boot - 获取环境变量
【发布时间】:2019-08-03 11:11:32
【问题描述】:

我必须得到一个环境变量,我不能注入。

@Component
@EnableConfigurationProperties
public class Client {

    @Autowired
    RestTemplate restTemplate;

    @Value("${BASE_URL}")
    private String baseUrl;

    public List<Car> getAllCars(){
        ResponseEntity<List<Car>> res = restTemplate.exchange(baseUrl.concat("/car"),HttpMethod.GET,null, 
                new ParameterizedTypeReference<List<Car>>() {});
        return res.getBody();
    }
}

我无法注入环境中的 basUrl。

有人能告诉我怎么做吗?

我阅读了以下几页,我是初学者,因为我什么都不懂。 https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html https://www.mkyong.com/spring-boot/spring-boot-configurationproperties-example/

我也试过

@Autowired
private Environment env;

结果总是为空。

【问题讨论】:

  • 您的属性文件是什么样的?它肯定在类路径上吗?
  • 通常环境属性不是大写的。也许你只是用错了钥匙
  • 我已经使用了@Value("${base.url}") 和@Value("${BASE_URL}") 并且总是一样的。
  • 您确定 BASE_URL 环境变量设置在您运行应用程序的同一上下文中吗?你能澄清一下你是如何设置环境变量的吗?
  • 我已经导出 BASE_URL=.... 并且它存在于获取这些变量时。

标签: java spring spring-boot environment-variables


【解决方案1】:

请尝试

@Value("#{systemProperties['BASE_URL']}")

【讨论】:

  • 对不起,我不想使用 application.proeries 我需要从环境变量中获取。
  • 在这种情况下,请尝试@Value("#{systemProperties['BASE_URL']}")
猜你喜欢
  • 2017-01-30
  • 2017-12-01
  • 2022-01-25
  • 2020-05-05
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 2020-01-18
相关资源
最近更新 更多