[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.

Overall configuration of
spring-boot-autoconfigure package spring-boot-starter is a very important package, which provides automatic configuration features, also commonly dependent, the default configuration set.

Dependent on
its three-dependent packages:

Base Package: spring-boot
optional feature dependencies: dependencies provide common default configuration provided by the user during actual use
test pack
optional feature dependent packages have spring-data-redis, validator, thymeleaf, websocket like. The following will explain the specific choose a few as examples.

原理br/>@EnableAutoConfiguration
@AutoConfigurationPackage
br/>@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
/**

AutoConfigurationImportSelector
auto-configuration selector, which type of automatic configuration selection.

selectImports
core methods: String [] selectImports (AnnotationMetadata annotationMetadata ), this method returns an array of full class name need autoconfiguration.
Class requires automatic configuration satisfies the following conditions:

META-INF / spring.factories the class key is org.springframework.boot.autoconfigure.EnableAutoConfiguration
@EnableAutoConfiguration the exclude annotations, excludeName class attributes represented spring.autoconfigure.exclude class configuration set (if present classpath , step 1 but does not exist, the exception thrown)
satisfies the condition includes three annotations: OnBeanCondition (eg: ConditionalOnBean, ConditionalOnMissingBean), OnClassCondition (eg: ConditionalOnClass, ConditionalOnMissingClass), OnWebApplicationCondition (eg: ConditionalOnWebApplication, ConditionalOnNotWebApplication)
Finally, activated AutoConfigurationImportEvent event.

getImportGroup DeferredImportSelector.Group and
results from different grouping ImportSelector

Automatic configuration sequence br /> AutoConfigurationSorter
@AutoConfigureOrder
@AutoConfigureBefore
br /> @ AutoConfigureAfter
AutoConfigurationSorter specific control sequencing logic
when @AutoConfigureOrder is Auto-configuration of the particular variant @Order, required the development of a custom configuration sequence can be used! AutoConfigureOrder. Absolute configuration control sequential application class.
The relative order and @AutoConfigureAfter @AutoConfigureBefore control application configuration class.

Specific training sequence as follows:

According to the class name in alphabetical ascending order
according to @AutoConfigureOrder value value (default: 0) in ascending order
according to @AutoConfigureBefore and @AutoConfigureAfter adjustment sorted
so @Order can control the order automatically configured like it?

@SpringBootApplication
2.1.8.RELEASE versions, this combination of notes notes as follows:

// omitted annotations without concern br /> @ SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan (excludeFilters @Filter = {(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter (type = FilterType.CUSTOM, = AutoConfigurationExcludeFilter classes. class)})
public @interface SpringBootApplication {
prior to the original @Configuration @SpringBootConfiguration, their meaning is as follows:

@Configuration class is the equivalent of
using the annotated classes offer Spring Boot application.
An application can contain only one @SpringBootConfiguration class, usually @SpringBootApplication it
AbstractDependsOnBeanFactoryPostProcessor
class implements BeanFactoryPostProcessor, will be executed at the right time in spring-boot the boot process
to inherit such a dynamic decision should specify the type of bean by the constructor what bean rely on.

BackgroundPreinitializer
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
automatically imported 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.factories 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
因此使用注解 AutoConfigureDataJpa 就相当于导入了 JpaRepositoriesAutoConfiguration
```、
DataSourceAutoConfiguration 等类。

使用如下:

@BootstrapWith(DataJpaTestContextBootstrapper.class)br/>@ExtendWith(SpringExtension.class)
@OverrideAutoConfiguration(enabled = false)
br/>@TypeExcludeFilters(DataJpaTypeExcludeFilter.class)
@Transactional
br/>@AutoConfigureCache
@AutoConfigureDataJpa
br/>@AutoConfigureTestDatabase
@AutoConfigureTestEntityManager
br/>@ImportAutoConfiguration
public @interface DataJpaTest {
// ...
br/>}
@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");
}

// ...
对常用工具的支持
以上原理是提供自动配置的基石,但实际在使用的时候,很多内容不需要任何(或极少量)配置就能直接使用,一方面是各 xxx-spring-boot-starter 中包含了 spring-boot-autoconfigure 并写了自动配置逻辑,一方面,是 spring-boot 官方在 spring-boot-autoconfigure 包中已经直接支持了。
spring-boot 对常用工具的支持
spring-boot 对常用数据源的支持

示例:gson 自动配置
支持有如下类:

GsonProperties
GsonBuilderCustomizer
GsonAutoConfiguration
GsonProperties class to obtain the configuration properties Gson

@ConfigurationProperties(prefix = "spring.gson")
public class GsonProperties {
private Boolean generateNonExecutableJson;
private Boolean excludeFieldsWithoutExposeAnnotation;
private Boolean serializeNulls;
private String dateFormat;
// ...
br/>}
@FunctionalInterface
public interface GsonBuilderCustomizer {
/**

  • Custom GsonBuilder
    * /
    void Customize (GsonBuilder gsonBuilder);
    }
    GsonAutoConfiguration used GsonProperties and GsonBuilderCustomizer (inner class implementation)

@Configurationbr/>@ConditionalOnClass(Gson.class)
@EnableConfigurationProperties(GsonProperties.class)
public class GsonAutoConfiguration {
br/>@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) {
     // ...
    }

Guess you like

Origin blog.51cto.com/14207399/2443606