Principle of SpringBoot automatic configuration
Automatic configuration:
pom.xml
-
Spring-boot-dependencies core dependencies are in the parent projectCopy the code
-
We do not need to specify versions when writing or importing springBoot dependencies, just because of the repository
starter
- This is the boot scenario for SpringBoot
- For example, spring-boot-starter-web automatically imports all the dependencies of the Web environment
- Springboot will turn all scenarios into individual initiators
- What are we going to use, just introduce the appropriate launcher
The main program
-
The @SpringBootApplication annotation is an application of SpringBootCopy the code
-
@SpringBootConfiguration SpringBootConfiguration @Configuration Spring Configuration class @Component indicates that this is also a Spring Component @enableAutoConfiguration Open automatically configure @ AutoConfigurationPackage automatic configuration package @ Import (AutoConfigurationPackages. The Registrar. Class) Import selector @ Import (AutoConfigurationImportSelector. Class) Import selector List < String > configurations = getCandidateConfigurations(annotationMetadata, attributes); Get all the configurationCopy the code
-
/ / get all the configuration of the protected a List < String > getCandidateConfigurations (AnnotationMetadata metadata, AnnotationAttributes attributes) { List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you " + "are using a custom packaging, make sure that file is correct."); return configurations; } protected Class<? > getSpringFactoriesLoaderFactoryClass() { return EnableAutoConfiguration.class; }Copy the code
-
META-INF/ Spring. factories auto-configuration core fileCopy the code
This file is filled with the names of the automatic configuration classes, which are loaded by annotations when the main program starts, saving us from writing configuration files
-
Why do I load a lot of autoconfiguration classes? Some work, some don't. Take springMVC's autoconfiguration class as an example: So this is springMVC's automatic Configuration class. @Configuration means it's a Configuration class. @conditionAlonClass this Configuration class will only be loaded if this condition is true. When we build project import MVC package to come into force this configuration class @ ConditionalOnWebApplicatio to come into force when the current is a web application Other configuration classes are similar on the configuration class through annotations to judge whether to take effect @Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class }) @ConditionalOnMissingBean(WebMvcConfigurationSupport.class) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10) @AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class }) public class WebMvcAutoConfiguration { public static final String DEFAULT_PREFIX = ""; public static final String DEFAULT_SUFFIX = ""; private static final String[] SERVLET_LOCATIONS = { "/" }; @Bean @ConditionalOnMissingBean(HiddenHttpMethodFilter.class) @ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled", matchIfMissing = false) public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() { return new OrderedHiddenHttpMethodFilter(); }Copy the code
-
The redis configuration file in springboot is as follows: spring.redis.host=127.0.0.1 spring.redis.port=6379Copy the code
We can inject them into a class with @ConfigurationProperties, or we can use @Value as a single binding, it’s easier to write in a configuration file, classes are too cumbersome, so what can we write in a configuration file?
This is the redis automatic Configuration class @configuration (proxyBeanMethods = false) @conditionalonClass (redisoperations.class) @ EnableConfigurationProperties (RedisProperties. Class) automatic configuration properties, Will be subject to RedisProperties class @ Import ({LettuceConnectionConfiguration. Class, JedisConnectionConfiguration.class }) public class RedisAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "redisTemplate") public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); return template; }Copy the code
This is the RedisProperties class and you can see @ConfigurationProperties, which tells you to inject the value of the configuration file, and you can see the prefix spring.redis is exactly the same as the redis configuration file, Redis. host="localhost". The following class host attribute has a default value of localhost, so we don't configure the connection address of redis in the configuration file. So you configure SpringBoot in your configuration file and you use yours, you don't configure it and you use the default configuration class, and similarly when we configure other properties, @configurationProperties (prefix = "spring.redis") public class RedisProperties {/** * Database index used by the connection factory. */ private int database = 0; /** * Connection URL. Overrides host, port, and password. User is ignored. Example: * redis://user:[email protected]:6379 */ private String url; /** * Redis server host. */ private String host = "localhost";Copy the code
Conclusion: The main program of SpringBoot uses @enableAutoConfiguration to enable automatic configuration, and scans all the auto-configuration classes in the meta-INF/Spring. factories. This configuration class save we write configuration files, through the @ ConditionalXXX should determine whether these configuration class, as long as the imported the corresponding starter, automatic configuration will take effect, through the @ EnableConfigurationProperties corresponding configuration on the class, Load the relevant configuration properties, if the configuration file has the configuration file, use the default, this is the principle of SpringBoot automatic configuration.