[A] source code to automatically configure these details do not know, do not say you will springboot

spring-boot with respect to the spring, a very important feature is the automatic configuration, the configuration is greater than the convention floor ideological success. xxx-spring-boot-starter capable of a series of guides out of the box, or requires minimal configuration (for beginner personnel) have done is because the default automatic configuration.

Autoconfiguration initialized at the outset some configurations, while providing access to modify the configuration.

the whole frame

spring-boot-autoconfigurePackage is spring-boot-startera very important package, which provides automatic configuration features, also commonly dependent, the default configuration set.

rely

It depends on three packages:

  • Base Package: spring-boot
  • Optional features dependencies: dependencies provide common default configuration provided by the user when actually used
  • Test Package

Optional features dependencies have spring-data-redis, validator, thymeleaf, websocket like. The following will explain the specific choose a few as examples.

principle

@EnableAutoConfiguration

@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
  /**
   *  当此名对应属性为 true 时,才开启自动配置
   */
  String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
  
  /**
   *  需要排除的类(通常当此类在类路径下时使用)
   */
  Class<?>[] exclude() default {};

  /**
   *  需要排除的类名(当此类不在类路径下时使用)
   */
  String[] excludeName() default {};
}

@AutoConfigurationPackage

The use of this type of annotation packet belongs to a registered spring bean.
This spring bean of beanName is AutoConfigurationPackages,
beanClass to BasePackages.

AutoConfigurationImportSelector

Selector auto-configuration, what type of automatic configuration selection.

selectImports

The core method: String[] selectImports(AnnotationMetadata annotationMetadata)This method returns an array of full class name to be automatically configured.
Class requires automatic configuration satisfies the following conditions:

  1. META-INF / spring.factories key is in org.springframework.boot.autoconfigure.EnableAutoConfigurationthe class
  2. @EnableAutoConfiguration the exclude annotations, excludeName class attributes represented spring.autoconfigure.exclude class configuration set (if present class path, but does not exist in step 1, the exception thrown)
  3. Contains three annotations satisfying the condition: OnBeanCondition(eg: ConditionalOnBean, ConditionalOnMissingBean), OnClassCondition(eg: ConditionalOnClass, ConditionalOnMissingClass), OnWebApplicationCondition(eg: ConditionalOnWebApplication, ConditionalOnNotWebApplication)

Finally, it will activate the AutoConfigurationImportEventevent.

getImportGroup and DeferredImportSelector.Group

Results from different grouping ImportSelector

Automatic configuration sequence

  • AutoConfigurationSorter
  • @AutoConfigureOrder
  • @AutoConfigureBefore
  • @AutoConfigureAfter

AutoConfigurationSorterSpecific sequencing control logic
@AutoConfigureOrderis @Orderat a particular variant Auto-configuration, it is necessary to develop a custom configuration order can be used @AutoConfigureOrder. Class control application configuration 绝对顺序.
@AutoConfigureBeforeAnd @AutoConfigureAftercontrolling the relative configuration of the sequential application class.

Specific training sequence as follows:

  1. According to the class name in accordance with 字母表递增sorting
  2. The @AutoConfigureOrdervalue (default: 0) 递增Sort
  3. According to @AutoConfigureBeforeand @AutoConfigureAfteradjust ordering

You @Ordercan control the order automatically configured like it?

@SpringBootApplication

2.1.8.RELEASE Version, this combination of notes notes as follows:

// 省略不需关心的注解
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

The original has been @Configurationchanged @SpringBootConfiguration, its meaning is as follows:

  • @Configuration equivalent class
  • Use the annotation class provides Spring Boot application.
    An application can contain only one @SpringBootConfiguration class, it usually @SpringBootApplication

AbstractDependsOnBeanFactoryPostProcessor

This class implements BeanFactoryPostProcessor, will be executed at the right time in spring-boot startup
inherit from this class by constructing dynamic decision should specify the type of bean which depends on the bean.

BackgroundPreinitializer

This class implements ApplicationListener<SpringApplicationEvent>
such features as: trigger early initialization in a background thread time-consuming task, such as:
ValidationInitializer, MessageConverterInitializer, JacksonInitializer, CharsetInitializer, ConversionServiceInitializer, MBeanFactoryInitializer, etc.

@ImportAutoConfiguration

Auto Import configuration class. From the source point of view, it is used to automatically configure the test time. The use of such annotations, also META-INF/spring.factoriesin the configuration, for example:

@ImportAutoConfiguration
public @interface AutoConfigureDataJpa {}
org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureDataJpa=\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration

Thus the use of annotations AutoConfigureDataJpais equivalent to introducing a JpaRepositoriesAutoConfiguration, DataSourceAutoConfiguration other categories.

Use as follows:

@BootstrapWith(DataJpaTestContextBootstrapper.class)
@ExtendWith(SpringExtension.class)
@OverrideAutoConfiguration(enabled = false)
@TypeExcludeFilters(DataJpaTypeExcludeFilter.class)
@Transactional
@AutoConfigureCache
@AutoConfigureDataJpa
@AutoConfigureTestDatabase
@AutoConfigureTestEntityManager
@ImportAutoConfiguration
public @interface DataJpaTest {
  // ...
}
@RunWith(SpringRunner.class)
@DataJpaTest
@TestPropertySource(properties = "spring.jpa.hibernate.use-new-id-generator-mappings=false")
public class DataJpaTestIntegrationTests {

    @Autowired
    private TestEntityManager entities;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private ExampleRepository repository;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void testEntityManager() {
        ExampleEntity entity = this.entities.persist(new ExampleEntity("spring", "123"));
        this.entities.flush();
        Object id = this.entities.getId(entity);
        ExampleEntity found = this.entities.find(ExampleEntity.class, id);
        assertThat(found.getName()).isEqualTo("spring");
    }
    
    // ...

Support for commonly used tools

The principle is the cornerstone of the above provide automatic configuration, but when in actual use, a lot of content without any (or very little) configuration can be used directly, on the one hand each xxx-spring-boot-starter contains a spring-boot- autoconfigure and wrote the automatic configuration logic, on the one hand, is spring-boot official in spring-boot-autoconfigure package has directly supported.
spring-boot support for commonly used tools
spring-boot support for common data sources

Example: gson autoconfiguration

Support the following categories:

  • GsonProperties
  • GsonBuilderCustomizer
  • GsonAutoConfiguration

GsonPropertiesGet Class Gsonconfiguration properties

@ConfigurationProperties(prefix = "spring.gson")
public class GsonProperties {
  private Boolean generateNonExecutableJson;
  private Boolean excludeFieldsWithoutExposeAnnotation;
  private Boolean serializeNulls;
  private String dateFormat;
  // ...
}
@FunctionalInterface
public interface GsonBuilderCustomizer {
    /**
     * 自定义 GsonBuilder
     */
    void customize(GsonBuilder gsonBuilder);
}

GsonAutoConfiguration Using (for internal class) GsonProperties and GsonBuilderCustomizer

@Configuration
@ConditionalOnClass(Gson.class)
@EnableConfigurationProperties(GsonProperties.class)
public class GsonAutoConfiguration {
    @Bean
    @ConditionalOnMissingBean
    public GsonBuilder gsonBuilder(List<GsonBuilderCustomizer> customizers) {
        GsonBuilder builder = new GsonBuilder();
        customizers.forEach((c) -> c.customize(builder));
        return builder;
    }

    @Bean
    @ConditionalOnMissingBean
    public Gson gson(GsonBuilder gsonBuilder) {
        return gsonBuilder.create();
    }

    @Bean
    public StandardGsonBuilderCustomizer standardGsonBuilderCustomizer(GsonProperties gsonProperties) {
        return new StandardGsonBuilderCustomizer(gsonProperties);
    }

    static final class StandardGsonBuilderCustomizer implements GsonBuilderCustomizer, Ordered {

        private final GsonProperties properties;

        StandardGsonBuilderCustomizer(GsonProperties properties) {
            this.properties = properties;
        }

        @Override
        public int getOrder() {
            return 0;
        }

        @Override
        public void customize(GsonBuilder builder) {
         // ...
        }

Public number: Yifei Come (focus on the Java domain knowledge in-depth study and orderly learning from the source to the principles of the system)

Yifei Come

Guess you like

Origin www.cnblogs.com/lw5946/p/11689890.html