有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java检查环境变量是否设置为运行时spring boot

我的springBoot应用程序使用一些在客户端上设置的环境变量,我在应用程序中设置它们。属性和一切都按预期工作。 所有客户端使用相同的变量。 现在出现了一个问题,即某个特定客户是否拥有某个变量集。您只需要在某些客户端上配置变量。 我们的想法是每个人只有一个代码,但如果我尝试上载应用程序的属性中包含应用程序中不存在的变量:

Unsatisfied dependency expressed through field 'config'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configClass': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'X' in value " ${INFO}"

是否有任何方法可以检查变量是否已设置且仅当我获取其内容时


共 (1) 个答案

  1. # 1 楼答案

    您可以简单地执行以下操作:

    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
    import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
    import org.springframework.context.ApplicationContextException;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.Ordered;
    import org.springframework.core.PriorityOrdered;
    import org.springframework.core.env.Environment;
    
    @Configuration
    public class VerifierBean implements BeanFactoryPostProcessor, PriorityOrdered {
    
       @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
          final Environment environment = configurableListableBeanFactory.getBean(Environment.class);
    
          if(environment.getProperty("property1.something") == null) {
             throw new ApplicationContextException("Missing property on context bootstrap" + " property1.something");
          }
       }
    
       @Override public int getOrder() {
          return Ordered.HIGHEST_PRECEDENCE;
       }
    }
    

    您将在console中看到类似的内容:

    [  restartedMain] o.s.boot.SpringApplication : Application run failed
    
    org.springframework.context.ApplicationContextException: Missing property on context bootstrap property1.something