官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 沾益县| 廉江市| 辛集市| 双城市| 岫岩| 襄垣县| 长阳| 普定县| 扶绥县| 泰兴市| 江安县| 河间市| 海盐县| 黄山市| 桐城市| 青阳县| 博兴县| 乌拉特中旗| 延庆县| 惠东县| 永福县| 荔波县| 康平县| 中西区| 云南省| 友谊县| 大渡口区| 平度市| 灵丘县| 文山县| 亳州市| 大竹县| 和平区| 永嘉县| 同德县| 宜昌市| 阿克| 泗水县| 永川市| 贵德县| 义乌市|