{{announcement.body}}
{{announcement.title}}

Magic Around Spring Boot Auto-Configuration

DZone 's Guide to

Magic Around Spring Boot Auto-Configuration

Spring, work your magic!

· Java Zone ·
Free Resource

Spring, work your magic!

Auto-configuration is probably one of the most important reasons why you would decide to use 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.

You may also like: How Spring Auto-Configuration Works

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 in an unusual way — 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.

Java




x


 
1
public class MyConfiguration {
2
 
          
3
    @Bean
4
    @ConditionalOnClass(MyBean2.class)
5
    public MyBean1 myBean1() {
6
        return new MyBean1();
7
    }
8
    
9
}



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

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

Java




xxxxxxxxxx
1
10


 
1
@Test(expected = NoSuchBeanDefinitionException.class)
2
public void testMyBean1() {
3
    final ApplicationContextRunner contextRunner = new ApplicationContextRunner();
4
    contextRunner.withUserConfiguration(MyConfiguration.class)
5
        withClassLoader(new FilteredClassLoader(MyBean2.class))
6
        .run(context -> {
7
            MyBean1 myBean1 = context.getBean(MyBean1.class);
8
            Assert.assertEquals("I'm MyBean1", myBean1.me());
9
        });
10
}



@ConditionalOnProperty

The @ConditionalOnProperty is a quite 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.

Java




xxxxxxxxxx
1


 
1
@Bean
2
@ConditionalOnProperty("myBean2.enabled")
3
public MyBean2 myBean2() {
4
    return new MyBean2();
5
}



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.

Java




xxxxxxxxxx
1
11


 
1
@Test(expected = NoSuchBeanDefinitionException.class)
2
public void testMyBean2Negative() {
3
    final ApplicationContextRunner contextRunner = new ApplicationContextRunner();
4
    contextRunner
5
        .withPropertyValues("myBean2.enabled=false")
6
        .withUserConfiguration(MyConfiguration.class)
7
        .run(context -> {
8
            MyBean2 myBean2 = context.getBean(MyBean2.class);
9
            Assert.assertEquals("I'm MyBean2", myBean2.me());
10
        });
11
}



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

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.

Java




xxxxxxxxxx
1


1
@Bean
2
@ConditionalOnProperty(value = "myBean5.disabled", havingValue = "false")
3
public MyBean5 myBean5() {
4
    return new MyBean5();
5
}
6
 
          



The current test is very similar to the previous one.


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 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.

Java




xxxxxxxxxx
1


 
1
@Bean
2
@ConditionalOnProperty("multipleBeans.enabled")
3
@ConditionalOnBean({MyBean1.class, MyBean2.class})
4
public MyBean4 myBean4() {
5
    return new MyBean4();
6
}



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

Java




xxxxxxxxxx
1
11


1
@Test(expected = NoSuchBeanDefinitionException.class)
2
public void testMyBean4Negative() {
3
    final ApplicationContextRunner contextRunner = new ApplicationContextRunner();
4
    contextRunner
5
        .withUserConfiguration(MyConfiguration.class)
6
        .withPropertyValues("multipleBeans.enabled")
7
        .run(context -> {
8
            MyBean4 myBean4 = context.getBean(MyBean4.class);
9
            Assert.assertEquals("I'm MyBean4", myBean4.me());
10
        });
11
}



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, which results in the availability of the bean.

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 annotations for such cases. So, we need to create class that extends the Spring AnyNestedCondition class, and defines all three conditions as shown below.

Java




xxxxxxxxxx
1
22


 
1
public class MyBeansOrPropertyCondition extends AnyNestedCondition {
2
 
          
3
    public MyBeansOrPropertyCondition() {
4
        super(ConfigurationPhase.REGISTER_BEAN);
5
    }
6
 
          
7
    @ConditionalOnBean(MyBean1.class)
8
    static class MyBean1ExistsCondition {
9
 
          
10
    }
11
 
          
12
    @ConditionalOnBean(MyBean2.class)
13
    static class MyBean2ExistsCondition {
14
 
          
15
    }
16
 
          
17
    @ConditionalOnProperty("multipleBeans.enabled")
18
    static class MultipleBeansPropertyExists {
19
 
          
20
    }
21
 
          
22
}



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

Java




xxxxxxxxxx
1


1
@Bean
2
@Conditional(MyBeansOrPropertyCondition.class)
3
public MyBean6 myBean6() {
4
    return new MyBean6();
5
}



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.


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.

Java




xxxxxxxxxx
1
11


 
1
@Test
2
public void testOrder() {
3
    final ApplicationContextRunner contextRunner = new ApplicationContextRunner();
4
    contextRunner
5
        .withUserConfiguration(MyConfiguration.class, MyConfigurationOverride.class)
6
        .withPropertyValues("myBean2.enabled")
7
        .run(context -> {
8
            MyBean2 myBean2 = context.getBean(MyBean2.class);
9
            Assert.assertEquals("I'm MyBean2 overridden", myBean2.me());
10
        });
11
}



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

Java




xxxxxxxxxx
1
13


 
1
public class MyBean2 {
2
 
          
3
    private String me = "I'm MyBean2";
4
 
          
5
    public String me() {
6
        return me;
7
    }
8
 
          
9
    void setMe(String me) {
10
        this.me = me;
11
    }
12
 
          
13
}



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

Java




xxxxxxxxxx
1
10


 
1
public class MyConfigurationOverride {
2
 
          
3
    @Bean
4
    public MyBean2 myBean2() {
5
        MyBean2 b = new MyBean2();
6
        b.setMe("I'm MyBean2 overridden");
7
        return b;
8
    }
9
    
10
}



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


Additional Conditional Annotations

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

Java




xxxxxxxxxx
1


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



Here's a test run under Java 8.


Summary

In this article, I demonstrated the most interesting features of Spring Boot auto-configuration. Building auto-configuration in Spring Boot is a rather simple thing to do, and maybe even fun? Here's the result of running our tests.

Further Reading

How Spring Auto-Configuration Works

7 Things to Know Before Getting Started With Spring Boot

Tutorial: Reactive Spring Boot, Part 5 — Auto-Configuration for Shared Beans

Topics:
java ,spring ,spring boot ,auto-configuration ,configuration ,annotations ,tutorial ,spring boot tutorial

Published at DZone with permission of Piotr Mińkowski , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}