Learning how auto-configuration works

Let's see what the @Conditional annotation does:

  • It allows conditional bean creation. It only creates a bean if other beans exist (or don't exist) as follows:
      @Bean 
      @ConditionalOnBean(name={"dataSource"}) 
      public JdbcTemplate jdbcTemplate(DataSource dataSource) { 
         return new JdbcTemplate(dataSource); 
      } 
  • Or @Conditional annotations allow us to create the bean by checking the type of other classes:
      @Bean 
      @ConditionalOnBean(type={DataSource.class}) 
      public JdbcTemplate jdbcTemplate(DataSource dataSource) { 
         return new JdbcTemplate(dataSource); 
      } 
  • There are many other options available under @Conditional annotation, as follows:
    • @ConditionalOnClass
    • @ConditionalOnProperty
    • @ConditionalOnMissingBean
    • @ConditionalOnMissingClass

Let's see what the auto-configuration class looks like in Spring Boot.

It is a pre-written Spring configuration in the org.springframework.boot.autoconfigure package in the spring-boot-autoconfigure JAR file:

@Configuration 
public class DataSourceAutoConfiguration implements EnvironmentAware { 
   ... 
   @Conditional(...) 
   @ConditionalOnMissingBean(DataSource.class) 
   @Import(...) 
   protected static class EmbeddedConfiguration { ... } 
         ... 
} 

Spring Boot defines many of these configuration classes. They are activated in response to dependencies on the classpath of your Spring application.

Let's see how to customize Spring Boot auto-configuration in your Spring application in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset