What can the Springboot configuration file write? How do you write it? Principle of Automatic Configuration
Property references that configuration files can configure
Principle of Automatic Configuration
- Spring Boot loads the main configuration class at startup, opening the automatic configuration function @EnableAutoConfiguration
- Role of Enalbel AutoConfiguration
- Import some components into the container using Enable AutoConfiguration Import Selector
- You can query the contents of the selectImports() method
```java public String[] selectImports(AnnotationMetadata annotationMetadata) { if (!this.isEnabled(annotationMetadata)) { return NO_IMPORTS; } else { try { AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader); AnnotationAttributes attributes = this.getAttributes(annotationMetadata); List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes); configurations = this.removeDuplicates(configurations); configurations = this.sort(configurations, autoConfigurationMetadata); Set<String> exclusions = this.getExclusions(annotationMetadata, attributes); this.checkExcludedClasses(configurations, exclusions); configurations.removeAll(exclusions); configurations = this.filter(configurations, autoConfigurationMetadata); this.fireAutoConfigurationImportEvents(configurations, exclusions); return (String[])configurations.toArray(new String[configurations.size()]); } catch (IOException var6) { throw new IllegalStateException(var6); } } } ```
- List < String > configurations = this. getCandidate Configurations (annotation Metadata, attributes); get candidate configurations
- SpringFactoriesLoader.loadFactoryNames();
- Scanning META-INF/spring.factories under all jar classpath
- Wrap the contents of the scanned files into properties objects
- Get the corresponding values of the EnableAutoConfiguration.class class (class name) from properties and add them to the container
- Add all EnableAutoConfiguration values configured in META-INF/spring.factories under the class path to the container
# PropertySource Loaders org.springframework.boot.env.PropertySourceLoader=\ org.springframework.boot.env.PropertiesPropertySourceLoader,\ org.springframework.boot.env.YamlPropertySourceLoader # Run Listeners org.springframework.boot.SpringApplicationRunListener=\ org.springframework.boot.context.event.EventPublishingRunListener # Application Context Initializers org.springframework.context.ApplicationContextInitializer=\ org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\ org.springframework.boot.context.ContextIdApplicationContextInitializer,\ org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\ org.springframework.boot.context.embedded.ServerPortInfoApplicationContextInitializer # Application Listeners org.springframework.context.ApplicationListener=\ org.springframework.boot.ClearCachesApplicationListener,\ org.springframework.boot.builder.ParentContextCloserApplicationListener,\ org.springframework.boot.context.FileEncodingApplicationListener,\ org.springframework.boot.context.config.AnsiOutputApplicationListener,\ org.springframework.boot.context.config.ConfigFileApplicationListener,\ org.springframework.boot.context.config.DelegatingApplicationListener,\ org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener,\ org.springframework.boot.logging.ClasspathLoggingApplicationListener,\ org.springframework.boot.logging.LoggingApplicationListener # Environment Post Processors org.springframework.boot.env.EnvironmentPostProcessor=\ org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor,\ org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor # Failure Analyzers org.springframework.boot.diagnostics.FailureAnalyzer=\ org.springframework.boot.diagnostics.analyzer.BeanCurrentlyInCreationFailureAnalyzer,\ org.springframework.boot.diagnostics.analyzer.BeanNotOfRequiredTypeFailureAnalyzer,\ org.springframework.boot.diagnostics.analyzer.BindFailureAnalyzer,\ org.springframework.boot.diagnostics.analyzer.ConnectorStartFailureAnalyzer,\ org.springframework.boot.diagnostics.analyzer.NoSuchMethodFailureAnalyzer,\ org.springframework.boot.diagnostics.analyzer.NoUniqueBeanDefinitionFailureAnalyzer,\ org.springframework.boot.diagnostics.analyzer.PortInUseFailureAnalyzer,\ org.springframework.boot.diagnostics.analyzer.ValidationExceptionFailureAnalyzer # FailureAnalysisReporters org.springframework.boot.diagnostics.FailureAnalysisReporter=\ org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter
Each xxxAutoConfiguration class is a component of the container that is added to the container; use them for automatic configuration
-
Each automatic configuration class has automatic configuration function.
-
Explain the principle of automatic configuration with Http Encoding AutoConfiguration as an example
@Configuration // Identify that this is a configuration class. Like previous configuration files, you can add components to containers. @EnableConfigurationProperties({HttpEncodingProperties.class}) // Enable the Configuration Properties function of the specified class, bind the corresponding HttpEncoding Properties. class class class in the configuration file, and add HttpEncoding Properties to the ioc container @ConditionalOnWebApplication // Spring underlying @Conditional annotation, according to different conditions, if the specified conditions are met, the configuration in the entire configuration class will take effect to determine whether the current application is a web application, and if so, the current configuration class will take effect. If not, it will not take effect. @ConditionalOnClass({CharacterEncodingFilter.class}) // To determine whether there is such a class in the current project, Spring Mvc filters for scrambling resolution @ConditionalOnProperty( prefix = "spring.http.encoding", value = {"enabled"}, matchIfMissing = true ) // Determine whether there is a configuration prefix spring.http.encoding in the configuration file; if it does not exist, it is valid even if spring.http.encoding.enable=true is not configured in the configuration file, it is also valid by default. public class HttpEncodingAutoConfiguration { // He's mapped to springboot's configuration file private final HttpEncodingProperties properties; // With only one parametric constructor, the value of the parameter is taken from the container. public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) { this.properties = properties; } @Bean // Add a component to the container, and some values of the build need to be retrieved from properties @ConditionalOnMissingBean({CharacterEncodingFilter.class}) public CharacterEncodingFilter characterEncodingFilter() { CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter(); filter.setEncoding(this.properties.getCharset().name()); filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST)); filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE)); return filter; }
Determine whether the configuration class will take effect based on the current conditions?
Once the configuration class takes effect, the configuration class adds various components to the container.
The attributes of these components are obtained from the corresponding properties classes, each of which is bound to the configuration file. -
All properties configurable in a configuration file are encapsulated in the xxxProperties class; what a configuration file can configure corresponds to this property class with reference to a function
HttpEncodingProperties.class@ConfigurationProperties( prefix = "spring.http.encoding" // Get the specified value from the configuration file and the properties of the bean for binding ) public class HttpEncodingProperties {
Essence:
- Sprboot startup loads a large number of configuration classes
- Let's see if we need a spring boot default autoconfiguration class
- Let's look at what components are configured in this configuration class (as long as we need to use components, we won't configure any more).
- Automatically configure classes in containers, and when you add components, you get some properties from the properties class. We can specify the values of these properties in the configuration file.
summary
XXXAutoConfiguration: Automatic Configuration Class
Adding components to containers
Correspond to one
XXXProperties: Encapsulates our related properties in the configuration file