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

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.

主站蜘蛛池模板: 阿拉善盟| 敦化市| 平阳县| 武夷山市| 乐昌市| 鄂托克旗| 洛扎县| 郎溪县| 定州市| 河津市| 玛纳斯县| 措勤县| 鄂尔多斯市| 乐业县| 曲水县| 庆元县| 泽普县| 东辽县| 含山县| 溧水县| 巍山| 水城县| 福安市| 巴彦淖尔市| 大方县| 乌恰县| 凤庆县| 洪雅县| 阿坝| 陆良县| 都昌县| 通海县| 龙井市| 辽宁省| 呼玛县| 永川市| 郯城县| 衡东县| 龙江县| 丹寨县| 汝阳县|