How Does Spring Boot Auto-Configuration Work?

DZone 's Guide to

How Does Spring Boot Auto-Configuration Work?

In this article, we take a look at how Spring Boot auto-configuration makes it easier than ever to have your beans configured for you.

· Java Zone ·
Free Resource

What Is It?

As its name implies, "autoconfiguration" helps you to configure your Spring Boot application automatically. More precisely, it automatically create beans for you! Strangely, it is a cool feature, but not applicable outside of Spring Boot. 

The Purpose and Method

The purpose is simple: to save you time when you create beans, which is usually done by yourself. It sounds like magic, but behind the scene, it's nothing fancy actually. 

It is simply a bunch of normal Spring configuration classes (like others with the same annotation @Configuration). 

The difference is that these configuration classes are using some different annotations:

  •  @ConditionalOnClass: acts only if a given class is on a classpath
  •  @ConditionalOnMissingBean: acts only if a given bean is not created
  •  @Conditional: acts only if given condition is met

In one sentence, generally, if a class is found in a classpath (@ConditionalOnClass) , and a bean is requested (@Autowired), but no others is creating it ( @ConditionalOnMissingBean), it'll create that bean. 

Let's have a look at one example:


What Does the Process Look?

You are asking for a bean, by using an annotation like  @AutowireSpring BeanFactory tries to find the bean for you.

If you have declared a bean by yourself (i.e.  @Configuration, @Component, @Service, etc.), Spring will pick that up and instantiate it for you. Otherwise, Spring will look into those auto-configuration classes (still @Configuration but with a @Conditional annotation), to find the suitable bean and instantiate it for you.

If still nothing is found, an exception is thrown by Spring, like NoSuchBeanDefinitionException.

How Do I Use This Feature, and Is There Anything I Can Do?

It is used via the annotation @EnableAutoConfiguration, which is included in  @SpringBootApplication already.

Spring does, however, leave options for you to have some control:

  1. You can tell Spring to disable certain auto-configuration classes.  (i.e.  @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) )
  2. You can tell Spring to include your own auto-configuration class. 
  3. You can declare your own bean, which will be respected by Spring and auto-configuration class will be ignored. This is done via @ConditionalOnMissingBean.
annotation, auto configuration, configuration classes, java, spring bean, spring beanfactory, spring boot

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}