A Magic Around Spring Boot Auto Configuration

A Magic Around Spring Boot Auto Configuration

Auto-configuration is probably one of the most important reasons you would decide to use such frameworks like Spring Boot. Thanks to that feature, it is usually enough just to include an additional library and override some configuration properties to successfully use it in your application. Spring provides an easy way to define auto-configuration using standard @Configuration classes.
Auto-configuration is one of the aspects related to Spring Boot Configuration. I have already described the most interesting features of externalized configuration in my article A Magic Around Spring Boot Externalized Configuration.

Example

The source code with example application is as usual available on GitHub. Here is the address of example repository: https://github.com/piomin/springboot-configuration-playground.git.

Testing Auto-configuration

Let us begin unusual – from testing. Spring Boot provides a very comfortable mechanism for auto-configuration testing. We just need to create an instance of ApplicationContextRunner in our JUnit test. With ApplicationContextRunner we can easily manipulate the classpath, include some property files into Spring context and finally declare a list of input configuration classes. Thanks to that we don’t even have to annotate our configuration class with @Configuration in order to be able to test it.

public class MyConfiguration {

   @Bean
   @ConditionalOnClass(MyBean2.class)
   public MyBean1 myBean1() {
      return new MyBean1();
   }
   
}

The myBean1 is dependent from MyBean2 class since it is annotated with @ConditionalOnClass. Let’s take a look on the list of all classes defined for our current demo.

spring-boot-auto-configuration-beans

As you see on the picture above MyBean2 class is available on classpath. Therefore, we need to remove it during the test to check the condition and get the expected NoSuchBeanDefinitionException exception. We may use FilteredClassLoader class for it.

@Test(expected = NoSuchBeanDefinitionException.class)
public void testMyBean1() {
   final ApplicationContextRunner contextRunner = new ApplicationContextRunner();
   contextRunner.withUserConfiguration(MyConfiguration.class)
      withClassLoader(new FilteredClassLoader(MyBean2.class))
      .run(context -> {
         MyBean1 myBean1 = context.getBean(MyBean1.class);
         Assert.assertEquals("I'm MyBean1", myBean1.me());
      });
}

@ConditionalOnProperty

The @ConditionalOnProperty is quite an interesting annotation. It allows configuration to be included only if an environment property exists, not exists or has a specific value. Let’s assume we have another bean myBean2 defined inside our configuration class.

@Bean
@ConditionalOnProperty("myBean2.enabled")
public MyBean2 myBean2() {
   return new MyBean2();
}

We will add property myBean2.enabled to ApplicationContextRunner during JUnit test. The result may be slightly surprising. The myBean2 bean is not available in the context (exception NoSuchBeanDefinitionException occurs). Why? Spring Boot documentation comes with the answer: By default, any property that exists and is not equal to false is matched. Since we set value false to our property (withPropertyValues("myBean2.enabled=false")), the result of test becomes clear.

@Test(expected = NoSuchBeanDefinitionException.class)
public void testMyBean2Negative() {
   final ApplicationContextRunner contextRunner = new ApplicationContextRunner();
   contextRunner
      .withPropertyValues("myBean2.enabled=false")
      .withUserConfiguration(MyConfiguration.class)
      .run(context -> {
         MyBean2 myBean2 = context.getBean(MyBean2.class);
         Assert.assertEquals("I'm MyBean2", myBean2.me());
      });
}

Any value different than false, including empty value, is ok. Here’s the example of a positive test.

spring-boot-auto-configuration-test-conditional-on-property

To create conditional bean dependent on a property value, we need to use field havingValue. Assuming we have following definition of bean, which is dependent on property myBean5.disabled, we need to override the rule that value false results in inaccessibility of the myBean5 bean.

@Bean
@ConditionalOnProperty(value = "myBean5.disabled", havingValue = "false")
public MyBean5 myBean5() {
   return new MyBean5();
}

The current test is very similar to the previous one.

spring-boot-auto-configuration-test-conditional-on-property-having-value

Multiple conditions

We may mix different conditional annotations on a single bean definition. We cannot duplicate the same annotation, but it is possible to add multiple classes, beans or properties inside a single conditional annotation. Each of those conditions is logically combined using AND. The following bean myBean4 is dependent from multipleBeans.enabled property, and myBean1, myBean2 beans.

@Bean
@ConditionalOnProperty("multipleBeans.enabled")
@ConditionalOnBean({MyBean1.class, MyBean2.class})
public MyBean4 myBean4() {
   return new MyBean4();
}

The following test verifies the case where only myBean2 is not available. It results in NoSuchBeanDefinitionException exception.

@Test(expected = NoSuchBeanDefinitionException.class)
public void testMyBean4Negative() {
   final ApplicationContextRunner contextRunner = new ApplicationContextRunner();
   contextRunner
      .withUserConfiguration(MyConfiguration.class)
      .withPropertyValues("multipleBeans.enabled")
      .run(context -> {
         MyBean4 myBean4 = context.getBean(MyBean4.class);
         Assert.assertEquals("I'm MyBean4", myBean4.me());
      });
}

Since myBean2 is dependent from myBean2.enabled property, we need to include it to the context during the test to verify a positive scenario. In the following JUnit test all three conditions for myBean4 are satisfied, what results in availability of the bean.

spring-boot-auto-configuration-multiple-conditions

Now, let’s consider the situation we would like to have the same conditions defined for our bean, but logically combined using OR. We don’t have any predefined annotation for such cases. So, we need to create a class that extends Spring AnyNestedCondition class, and defines all three conditions as shown below.

public class MyBeansOrPropertyCondition extends AnyNestedCondition {

    public MyBeansOrPropertyCondition() {
        super(ConfigurationPhase.REGISTER_BEAN);
    }

    @ConditionalOnBean(MyBean1.class)
    static class MyBean1ExistsCondition {

    }

    @ConditionalOnBean(MyBean2.class)
    static class MyBean2ExistsCondition {

    }

    @ConditionalOnProperty("multipleBeans.enabled")
    static class MultipleBeansPropertyExists {

    }

}

The class defined above needs to be used as a condition for our new bean. Here’s myBean6 definition.

@Bean
@Conditional(MyBeansOrPropertyCondition.class)
public MyBean6 myBean6() {
   return new MyBean6();
}

In the following test only the condition with myBean1 is satisfied. Since, all our three conditions are logically connected using OR myBean6 is available in the context. It is also worth mention that Spring Boot provides class NoneNestedCondition for building negative conditions.

spring-boot-auto-configuration-any-nested-condition

Load order of auto-configuration

We may define multiple @Configuration in our application. When having multiple configuration beans we may easily control a load order by using annotations @AutoConfigureAfter, @AutoConfigureBefore or @AutoConfigureOrder. In the test with ApplicationContextRunner the load order is just represented by the order arguments used in withUserConfiguration method.

@Test
public void testOrder() {
   final ApplicationContextRunner contextRunner = new ApplicationContextRunner();
   contextRunner
      .withUserConfiguration(MyConfiguration.class, MyConfigurationOverride.class)
      .withPropertyValues("myBean2.enabled")
      .run(context -> {
         MyBean2 myBean2 = context.getBean(MyBean2.class);
         Assert.assertEquals("I'm MyBean2 overridden", myBean2.me());
      });
}

Let’s consider the situation where we have two declarations of the same bean in two configuration classes. Here’s our bean.

public class MyBean2 {

   private String me = "I'm MyBean2";

   public String me() {
      return me;
   }

   void setMe(String me) {
      this.me = me;
   }

}

We are defining a second Spring configuration class that overrides myBean2 declaration.

public class MyConfigurationOverride {

   @Bean
   public MyBean2 myBean2() {
      MyBean2 b = new MyBean2();
      b.setMe("I'm MyBean2 overridden");
      return b;
   }
   
}

What would be the result of the operation visible above? It overrides existing bean definitions as shown below.

spring-boot-auto-configuration-order

Additional conditional annotations

There are some additional conditional annotations like @ConditionalOnExpression, @ConditionalOnSingleCandidate or @ConditionalOnWebApplication. For more details you may to Spring Boot documentation. There is also @ConditionalOnJava, which allows you to define a version of Java under which a defined bean should be available. Here’s the definition where MyBean3 is registered only if the Java version is newer than 8.

@Bean
@ConditionalOnJava(range = ConditionalOnJava.Range.EQUAL_OR_NEWER, value = JavaVersion.NINE)
public MyBean3 myBean3() {
   return new MyBean3();
}

Here’s a test run under Java 8.

spring-boot-auto-configuration-java-version

Summary

In this article I demonstrated you the most interesting features of Spring Boot Auto Configuration. Building auto-configuration in Spring Boot is a rather simple thing to do, and even may be fun 🙂 Here’s the result of running our tests.

spring-boot-auto-configuration-tests

8 COMMENTS

comments user
Anbu

Excellent Article.

    comments user
    Piotr Mińkowski

    Thanks 🙂

comments user
Anbu

Excellent Article.

    comments user
    Piotr Mińkowski

    Thanks 🙂

comments user
Dhiraj

Excellent article. Shared on my blog too – https://www.devglan.com/programming/springframework-article-feeds

    comments user
    Piotr Mińkowski

    Thanks 🙂

comments user
Dhiraj

Excellent article. Shared on my blog too – https://www.devglan.com/programming/springframework-article-feeds

    comments user
    Piotr Mińkowski

    Thanks 🙂

Leave a Reply