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

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.

主站蜘蛛池模板: 商河县| 六枝特区| 清新县| 赤峰市| 兴安盟| 石嘴山市| 吴忠市| 嵩明县| 砀山县| 伊吾县| 土默特右旗| 遂宁市| 利川市| 绥芬河市| 长武县| 武穴市| 多伦县| 会同县| 徐汇区| 巴塘县| 苏尼特右旗| 大方县| 盱眙县| 正宁县| 庐江县| 乌鲁木齐市| 桑日县| 万安县| 旬邑县| 博野县| 张家港市| 磐安县| 庆云县| 马尔康县| 韩城市| 玉树县| 司法| 阳高县| 奉化市| 滦平县| 海阳市|