SpringBoot automatic configuration of magic

Spring automatic configuration

Speaking from @SpringBootApplication comment

SpringBootAccording to the class will automatically configure the class path, eliminating the need to write cumbersome xmlconfiguration file. Originally based on xmlthe configuration beanbased on the Java code programming mode, and may be configured conditioned, depending on the scene configuration also will be different. It is not very smart

In order to understand SpringBootthe principle of automatic configuration, from the most simple SpringBootto start a startup class, look at a simple example to start

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}

SpringBootStart the application is very simple, it is a mainmethod, and then execute SpringApplicationthe run method. First do not care how run method is executed. We look at the SpringBootapplication of core notes@SpringBootApplication

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
        @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
    .....
}

Check the annotated source code shows that it is a combination comment.

Respectively see what each annotation

@SpringBootConfiguration

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}

The comment is seen that @Configurationcomment, what the configuration of a class of the notes, in SpringBootcommon in.

@CompontScanWhat package does not scan or scan the specified comment.

The SpringBootapplication has automatic configuration magic annotations are @EnableAutoConfiguraion. The notes can be automatically configured to allow SpringBoot current project based on the class path dependence, so SpringBoot can automatically configure mainly because @EnableAutoConfiguraion comment on SpringBoot applications to achieve, so join the annotation on the class starts, it will automatically open configuration.

So, this is how to achieve automated annotation to configure it. Next we want to find out.

Automatic Configuration notes behind

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
    .....
}

The annotation is a combination of notes, there is a @Import(AutoConfigurationImportSelector.class), then @Importwhat is the role it notes, view @Importsource code annotations, written Indicates one or more {@link Configuration @Configuration} classes to import.Provides functionality equivalent to the {@code <import/>} element in Spring XML., notes show that this annotation indicates configuration classes you want to import, and in function Spring XML配置of <import>the same

Here that @Importone of the imported AutoConfigurationImportSelectorand what role do? SUMMARY The following comments can be known, @Importallowing import ImportSelector,ImportBeanDefinitionRegistrarof the implementation class, as well as ordinary class (in the version 4.2)

Allows for importing {@code @Configuration} classes, {@link ImportSelector} and {@link ImportBeanDefinitionRegistrar} implementations, as well as regular component classes (as of 4.2; analogous to {@link AnnotationConfigApplicationContext#register}).

To here, to say a comment related things and @Import, Spring Framework itself provides a number of functions that begin with annotations Enable, known under the name of which is open, such as @EnableScheduling, @EnableCaching, @EnableMBeanExportetc., @EnableAutoConfigurationideas and these notes are actually the same of.

@EnableSchedulingBy @Importthe Spring Framework bean scheduling related definitions are loaded into IoC container. @EnableMBeanExportThrough @ImportJMX bean definition on IoC container will be loaded into.

@EnableAutoConfigurationAlso by means @Importof help, all the bean definitions in line with the conditions of auto-configuration is loaded into the IoC container.

Then focus on what EnableAutoConfigurationImportSelector this role Yes. The main is to use Spring 4 provides the SpringFactoriesLoadertools. By SpringFactoriesLoader.loadFactoryNames()reading the following ClassPath META-INF/spring.factoriesfile

EnableAutoConfigurationImportSelectorBy reading spring.factoriesof the key org.springframework.boot.autoconfigure.EnableAutoConfigurationvalue. As spring-boot-autoconfigure-1.5.1.RELEASE.jarthe spring.factoriesfile contains the following:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\

If we define a new starterword, but also in that starterof jarproviding package  META-INFO/spring.factoriesfiles, and configure org.springframework.boot.autoconfigure.EnableAutoConfigurationthe corresponding configuration class

From EnableAutoConfigurationCacheAutoConfiguration looking for a configuration class

@Configuration
@ConditionalOnClass(CacheManager.class)
@ConditionalOnBean(CacheAspectSupport.class)
@ConditionalOnMissingBean(value = CacheManager.class, name = "cacheResolver")
@EnableConfigurationProperties(CacheProperties.class)
@AutoConfigureAfter({ CouchbaseAutoConfiguration.class, HazelcastAutoConfiguration.class,
        HibernateJpaAutoConfiguration.class, RedisAutoConfiguration.class })
@Import(CacheConfigurationImportSelector.class)
public class CacheAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public CacheManagerCustomizers cacheManagerCustomizers(
            ObjectProvider<List<CacheManagerCustomizer<?>>> customizers) {
        return new CacheManagerCustomizers(customizers.getIfAvailable());
    }
    .......
}

This is a @Configurationconfiguration class that contains @Beanthe method's return value will be registered as abean

In this way we see a lot of class and condition configuration notes

Notes Configuration main condition is @Conditionalthat the annotation specifies a realization Conditionof the class, the class implements matchsthe method, if the method returns true, the @Conditionalmodified class or method will create bean. In order to facilitate Spring4it has helped us achieve some common conditions configuration notes

@ConditionalOnBean
@ConditionalOnClass
@ConditionalOnExpression
@ConditionalOnMissingBean
@ConditionalOnMissingClass
@ConditionalOnNotWebApplication

So far, we have analyzed the SpringBootbasic principle of the automation configuration, then we will write aspring-boot-starter

Guess you like

Origin www.cnblogs.com/watertreestar/p/11780286.html