Search code examples
spring-bootspring-cloudspring-cloud-config

Custom Bean not loaded in Spring Boot Cloud AutoConfiguration Class


I want to provide a specific Bean, so that this Bean overrides the Bean in a Spring Cloud AutoConfiguration class.

First try

Therefore I've created a Configuration class:

@Configuration
public class MyLocalConfig {
  @Bean
  public ApiClient apiClient() throws IOException {
    return ClientBuilder.standard(false).build();
  }
}

Prioritizing by using @Primary or @Order annotations does not help.

Second try (EDIT)

I also tried to use an AutoConfiguration. But even the @AutoConfigureBefore Annotation is ignored.

@Configuration
@AutoConfigureBefore(KubernetesClientAutoConfiguration.class)
public class LocalKubeAutoConfiguration {
  @Bean
  public ApiClient apiClient() throws IOException {
    return ClientBuilder.standard(false).build();
  }
}

My Configuration class Beans are always instantiated after the Beans in KubernetesClientAutoConfiguration class. Therefore the AutoConfiguration class does not use my Bean.

The doc says: At any point, you can start to define your own configuration to replace specific parts of the auto-configuration.

Questions:

  • What's my mistake?
  • How can I prioritize the configurations?

Here's my other code:

Main Class

@SpringBootApplication
public class SpringBootAdminApp {
  public static void main(String[] args) {
    SpringApplication.run(SpringBootAdminApp.class, args);
  }
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>testme</artifactId>
    <version>1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-kubernetes-client-all</artifactId>
            <version>2.0.2</version>
        </dependency>
    </dependencies>
</project>

Solution

  • Spring Boot Cloud uses Bootstrap Configuration to load the configurations.

    By default, bootstrap properties (not bootstrap.properties but properties that are loaded during the bootstrap phase) are added with high precedence, so they cannot be overridden by local configuration.

    Therefore I have to add a BootstrapConfiguration:

    org.springframework.cloud.bootstrap.BootstrapConfiguration=\
    com.demo.LocalKubeConfig
    

    The Bean in the BootstrapConfiguration will be loaded before KubernetesClientAutoConfiguration.