Springcloud不能识别bootstrap配置文件
方法一:引用spring-cloud-starter-bootstrap包(推荐)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
方法二:设置spring.cloud.bootstrap.enabled=true
1、在main方法设置
@EnableDiscoveryClient
@SpringBootApplication
public class application {
public static void main(String[] args) {
args = Arrays.copyOf(args, args.length + 1);
args[args.length - 1] = "--spring.cloud.bootstrap.enabled=true";
SpringApplication.run(application .class, args);
}
}
2、使用ApplicationListener添加
@Component
public class StartOnApplication implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment environment=event.getEnvironment();
Properties properties=new Properties();
properties.setProperty("spring.cloud.bootstrap.enabled","true");
environment.getPropertySources().addLast(new PropertiesPropertySource("application1",properties));
}
}
3、运行时配置,idea如下
原因分析:
BootstrapApplicationListener.class
类
PropertyUtils
类
public abstract class PropertyUtils {
/**
* Property name for checking if bootstrap is enabled.
*/
public static final String BOOTSTRAP_ENABLED_PROPERTY = "spring.cloud.bootstrap.enabled";
/**
* Property name for spring boot legacy processing.
*/
public static final String USE_LEGACY_PROCESSING_PROPERTY = "spring.config.use-legacy-processing";
/**
* Property name for bootstrap marker class name.
*/
public static final String MARKER_CLASS = "org.springframework.cloud.bootstrap.marker.Marker";
/**
* Boolean if bootstrap marker class exists.
*/
public static final boolean MARKER_CLASS_EXISTS = ClassUtils.isPresent(MARKER_CLASS, null);
private PropertyUtils() {
throw new UnsupportedOperationException("unable to instatiate utils class");
}
/**
*判断"spring.cloud.bootstrap.enabled"指定值是否获取到,没有取默认值false;或者判断`Marker`类是否存在。
*`Marker`类存在`spring-cloud-starter-bootstrap.x.x.jar`里面
*/
public static boolean bootstrapEnabled(Environment environment) {
return environment.getProperty(BOOTSTRAP_ENABLED_PROPERTY, Boolean.class, false) || MARKER_CLASS_EXISTS;
}
/**
*该值默认为false,"spring-boot-X.x,jar"包中的additional-spring-configuration-metadata.json文件中
*/
public static boolean useLegacyProcessing(Environment environment) {
return environment.getProperty(USE_LEGACY_PROCESSING_PROPERTY, Boolean.class, false);
}
}
总结:BootstrapApplicationListener
类会判断是否加载名为bootstrap的配置文件,PropertyUtils
类会判断spring.cloud.bootstrap.enabled的值是否为true,或者Marker类是否存在。满足条件则会加载bootstrap的配置文件。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?