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的配置文件。

作者:Jeebiz  创建时间:2024-10-04 23:58
最后编辑:Jeebiz  更新时间:2024-10-05 00:00