gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:30:42 27 4
gpt4 key购买 nike

我的 springBoot 应用程序使用了在我的客户端上设置的一些环境变量,我将它们设置在我的 application.properties 中,一切都按预期工作。所有客户端都使用相同的变量。现在出现了一个问题,特定客户可能具有或不具有特定的变量集。您只需要在某些客户端上配置该变量。这个想法是为每个人只有一个代码,但如果我尝试上传应用程序,其属性中包含应用程序中不存在的变量:

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

有什么方法可以检查变量是否已设置以及仅当我获取其内容时才检查吗?

最佳答案

你可以简单地做这样的事情:

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

你会在控制台中看到类似这样的内容:

[  restartedMain] o.s.boot.SpringApplication : Application run failed

org.springframework.context.ApplicationContextException: Missing property on context bootstrap property1.something

关于java - 检查环境变量是否设置为运行时spring boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58012654/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com