简体   繁体   English

如何从 Spring Boot 获取操作系统环境变量?

[英]How to get OS environment variable from Spring Boot?

I am novice to java and spring framework.我是java和spring框架的新手。 My questions is how to inject OS(ubuntu) environment variable to spring boot bean.我的问题是如何将 OS(ubuntu) 环境变量注入 spring boot bean。 What I tried:我试过的:

@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
 @Value("${COMPONENT_PARAM_CORS}")
 private String COMPONENT_PARAM_CORS;

 @Override
 public void addCorsMappings(CorsRegistry registry) {
  registry.addMapping("/"+COMPONENT_PARAM_CORS);
 }
}

export COMPONENT_PARAM_CORS=**导出 COMPONENT_PARAM_CORS=**

printenv打印环境

says me that its present, but when I try to mvn clean install: error occured告诉我它存在,但是当我尝试 mvn clean install 时:发生错误

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error 
creating bean with name 'corsConfig': Injection of autowired dependencies 
failed; nested exception is java.lang.IllegalArgumentException: Could not 
resolve placeholder 'COMPONENT_PARAM_CORS' in value "${COMPONENT_PARAM_CORS}"
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 
'COMPONENT_PARAM_CORS' in value "${COMPONENT_PARAM_CORS}"

and then my unit test also droped (I am trying to search this error, but all topics is old and uses params from application.properties, but I need to use env var not application.properties)然后我的单元测试也下降了(我试图搜索这个错误,但所有主题都是旧的并且使用来自 application.properties 的参数,但我需要使用 env var 而不是 application.properties)

You can use System.getenv(<environment name>) method to retrieve an environment variable value.您可以使用System.getenv(<environment name>)方法来检索环境变量值。 Like:喜欢:

registry.addMapping("/" + System.getenv("COMPONENT_PARAM_CORS"));

or with default value:或使用默认值:

registry.addMapping("/" + System.getenv().getOrDefault("COMPONENT_PARAM_CORS", "DEFAULT_VALUE"))

More information here https://docs.oracle.com/javase/tutorial/essential/environment/env.html这里有更多信息https://docs.oracle.com/javase/tutorial/essential/environment/env.html

If you really want to inject variable value you can modify your code to something like:如果你真的想注入变量值,你可以将代码修改为:

@Value("#{systemEnvironment['COMPONENT_PARAM_CORS'] ?: 'DEFAULT_VALUE'}")
private String COMPONENT_PARAM_CORS;

You should use System.getenv() , for example:您应该使用System.getenv() ,例如:

import java.util.Map;

public class EnvMap {
    public static void main (String[] args) {
        Map<String, String> env = System.getenv();
        for (String envName : env.keySet()) {
            System.out.format("%s=%s%n",
                              envName,
                              env.get(envName));
        }
    }
}

Please refer to This documentation and this question .请参阅此文档此问题

@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {

 @Value("#{systemEnvironment['COMPONENT_PARAM_CORS']?:'**'}")
 private String COMPONENT_PARAM_CORS;

 @Override
 public void addCorsMappings(CorsRegistry registry) {
  registry.addMapping("/"+COMPONENT_PARAM_CORS);
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在我的Spring Boot应用程序中从AWS访问环境变量 - How to access Environment Variable from AWS in my spring boot application 如何在Spring Boot中为类级别注释@PropertySource获取OS环境变量? - How to fetch OS environment variable for class level annotation @PropertySource in Spring Boot? Spring 使用环境变量进行引导验证 - Spring Boot Validation with environment variable Spring-如何使应用程序从属性文件读取环境变量 - Spring - How to get app to read environment variable from properties file Spring Boot 2 没有选择操作系统环境变量 - Spring Boot 2 not picking up OS environment variables 如何从Jackson @JsonCreator构造函数访问Spring Boot环境变量 - How can I access a Spring Boot environment variable from a Jackson @JsonCreator constructor Spring 引导 + Docker 撰写:如何覆盖“地图” <string, list<string> &gt;' 来自 yaml 属性的环境变量</string,> - Spring Boot + Docker Compose: How to override 'Map<String, List<String>>' environment variable from yaml properties Java-从Spring Boot应用程序获取变量 - Java - Get variable from Spring Boot Application 如何在spring boot中使用环境变量动态设置tableName? - How to set tableName dynamically using environment variable in spring boot? 从spring-boot环境获取属性映射 - Get Map of properties from spring-boot Environment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM