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

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.

主站蜘蛛池模板: 大竹县| 南宫市| 陆良县| 女性| 深州市| 新兴县| 泗水县| 将乐县| 静安区| 珲春市| 和硕县| 湛江市| 浦江县| 清水县| 蓬溪县| 缙云县| 黑水县| 江永县| 四平市| 大埔县| 淄博市| 澜沧| 临朐县| 共和县| 沁阳市| 新兴县| 西和县| 盐边县| 曲阜市| 汝城县| 柯坪县| 五台县| 建瓯市| 茌平县| 宣汉县| 贵港市| 长沙县| 岑巩县| 镇安县| 德昌县| 会昌县|