SpringBoot introduction
- The basic concept
- SpringBoot parent project
-
- spring-boot-starter
- @SpringBootApplication
- SpringBoot configuration
-
-
- The configuration file
- yml
-
-
- YAML basic syntax
-
- The @Value Value is compared to the @ConfigurationProperties Value
- Configuration file Injection Value Numerical verification (JSR303)
- @ PropertySource and @ ImportResource
- Configuration file placeholder
- Profile
- Configuration file loading location
- Load order of external configuration
-
- Principle of Automatic configuration
- conclusion
The basic concept
-
Benefits of SpringBoot:
- You can create a standalone Spring application
- SpringBoot is embedded in Tomcat,Jetty, and Unsertow without the need to deploy a WAR file
- Obtain the starter from Maven as required
- Spring is automatically configured
- Provides production-ready functionality, including metrics, health checks, and external configuration
SpringBoot parent project
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.9. RELEASE</version>
<relativePath>. /.. /spring-boot-dependencies</relativePath>
</parent>
Copy the code
- Add dependencies to the SpringBoot application. Add dependencies to the SpringBoot application. Add dependencies to the SpringBoot application.
spring-boot-starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Copy the code
- Spring-boot-starter: indicates the initiator in springboot scenarios
- Spring-boot-starter-web: imports components on which the Web module runs properly
- SpringBoot extracts all the functional scenarios as starter initiators. You just need to introduce these starter dependencies in the project’s POM.xml, and all the dependencies for the relevant scenarios will be imported.
@SpringBootApplication
- @springBootApplication: Identifies the main configuration class in SpringBoot. SpringBoot will run the main method of that class to start the SpringBoot application.
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration //SpringBoot configuration class, similar to configuration files. Configuration classes are also components in the container. The annotation identifies a SpringBoot configuration class on the class
@EnableAutoConfiguration // Enable SpringBoot automatic configuration
@ComponentScan( excludeFilters = {@Filter( type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class} ), @Filter( type = FilterType.CUSTOM, classes = {AutoConfigurationExcludeFilter.class} )} )
public @interface SpringBootApplication {
@AliasFor( annotation = EnableAutoConfiguration.class, attribute = "exclude" )Class<? >[] exclude()default {};
@AliasFor( annotation = EnableAutoConfiguration.class, attribute = "excludeName" )
String[] excludeName() default {};
@AliasFor( annotation = ComponentScan.class, attribute = "basePackages" )
String[] scanBasePackages() default {};
@AliasFor( annotation = ComponentScan.class, attribute = "basePackageClasses" )Class<? >[] scanBasePackageClasses()default {};
}
Copy the code
- @springBootConfiguration: SpringBoot configuration class, similar to a configuration file. Configuration classes are also components in the container. The annotation identifies a SpringBoot configuration class on the class
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration // Indicates that this class is a Spring configuration class
public @interface SpringBootConfiguration {
@AliasFor( annotation = Configuration.class )
boolean proxyBeanMethods(a) default true;
}
Copy the code
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component // Indicates that the class is a component of Spring
public @interface Configuration {
@AliasFor( annotation = Component.class )
String value default "";
boolean proxyBeanMethods(a) default true;
}
Copy the code
- @enableAutoConfiguration: Enables automatic SpringBoot configuration
package org.springframework.boot.autoconfigure;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; Class<? >[] exclude()default {};
String[] excludeName() default {};
}
Copy the code
-
@AutoConfigurationPackage: The auto-configuration package is done via @import ({mail.class}). Look at the Registrar source to find the package containing the main configuration class, the @SpringBootApplication tagged class, and then scan all the components in the sub-packages into the Spring container
-
The @import is the underlying Spring annotation that imports a component to the container, specified via Registr.class.
-
AutoConfigurationImportSelector: import component selector, all you need to import the components of the name of the class to return, such components can be added into the container
- Automatic configuration classes are imported into the container: that is, all the components of the scene are imported into the container and configured. This eliminates the need to manually write configurations and inject functional components
-
SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,classLoader) :
- Get the value specified by EnableAutoConfiguration from meta-INF/Spring.Factories under the classpath
-
Process summary:
- SpringBoot gets the value specified by EnableAutoConfiguration from the META-INF/ Spring. factories in the classpath at startup
- Import these values into the container as auto-configuration classes, and the auto-configuration classes take effect to do the configuration.
-
The entire J2EE integration solution and auto-configuration is in spring-boot-Autoconfigure-2.0.1.release.jar
Resources folder in the SpringBoot project:
- Static: Saves all static resources, such as JS, CSS, and images
- Templates: Saves all the template pages. The default JAR package in SpringBoot uses embedded Tomcat and does not support JSP pages by default. You can use template engines: Freemarker, Thymeleaf
- Application. The properties: SpringBoot application configuration file, you can modify some of the default Settings
SpringBoot configuration
The configuration file
SpringBoot uses a global configuration file with a fixed configuration file name:
- application.properties
- application.yml
- The configuration file is used to change the default SpringBoot automatic configuration.
yml
- Yml (YAML Ain’t Markup Language) is data-centric and is better for configuration files than JSON, XML, etc.
YAML basic syntax
-
Key: value (Indicates a pair of key-value pairs. Value must be preceded by a space.
-
The hierarchy is denoted by indented Spaces. Any left-aligned column is a 1 of the same hierarchy. 2. The number of indent Spaces is not important, as long as elements of the same level are aligned to the left
-
Properties and values are case sensitive
-
Value written as:
- Literals: ordinary values (numbers, strings, Booleans)
-
Key: value: literal value written directly. Strings are not quoted by default.
-
Single quotes – escape characters are printed as normal strings
-
Double quotes – Escape characters are converted to format
-
Objects, maps (properties and values, key-value pairs) :
- Object or key: value
friends:
lastName: Chova
firstName: Vea
Copy the code
Written in line:
friends: {lastName: Chova.firstName: Vea}
Copy the code
-
Array (List, Set)
- The – value represents the element in the array
pets:
- dog
- cat
- pig
Copy the code
Written in line:
pets: [dog.cat.pig]
Copy the code
The @Value Value is compared to the @ConfigurationProperties Value
@Value | @ConfigurationProperties | |
---|---|---|
function | Specify injections one by one on the property | Batch injection of properties in the configuration file |
Loose binding (loose syntax) | Does not support | support |
SpEL | support | Does not support |
JSR303 data verification | Does not support | support |
Complex type encapsulation | Does not support | support |
- Use @value if we just need to get the Value of a configuration file in some business logic
- If a JavaBean needs to map to a configuration file, use @ConfigurationProperties
Configuration file Injection Value Numerical verification (JSR303)
- You have to use @ConfigurationProperties
- JSR303 data verification: @Validate-@Email
@ PropertySource and @ ImportResource
- PropertySource: Loads the specified configuration file
@PropertySource(value = {"classpath:person.properties"})
Copy the code
- ImportResource: Import the Spring configuration file for the configuration file to take effect
@ImportResource(locations={"classpath:beans.xml"})
Copy the code
- SpringBoot recommended way to add components to a container: Full annotations are recommended 1. Configuration class – Spring configuration file 2. Use @Bean to add components to the container in the configuration class
Configuration file placeholder
- RandomValuePropertySource: the configuration file can use a random number
1. ${random. Value} 2. ${random. Int} 3. ${random. Int (10)} 4. ${random. Int [1024655] 36}Copy the code
- ${app.name: default} to specify the default value if the value of the attribute cannot be found
Profile
-
Multiple Profile files: 1. When writing a Profile, the file name can be Application -{Profile}. Properties /yml 2. The default configuration of application.properties is used
-
Yml supports the multi-document block approach
- Divide document blocks with “–“
---
Copy the code
Activate the specified Profile: 1. Specify activation in the main Profile application.properties:
spring.profiles.active=dev
Copy the code
2. Command line activation :(Program arguments)
--spring.profiles.active=dev
Copy the code
3. VM parameter activation :(VM options)
-Dspring.profiles.active=dev
Copy the code
Configuration file loading location
- The SpringBoot startup scans the application.properties or application.yml file in the following location as the default SpringBoot configuration file
- file:./config/
- file:./
- classpath:/config
- classpath:/
- In order of priority, all files will be loaded, complementary configuration. High-priority content overwrites low-priority content.
- You can change the default configuration location by configuring **- -spring.config.location** : After the project is packaged, specify the new location of the configuration file when the project is started using command line arguments. The specified configuration file and the default loaded configuration file will work together to supplement the configuration.
Load order of external configuration
- SpringBoot supports multiple external configuration modes with the following priorities: 1. Command-line arguments (- -, multiple commands separated by Spaces) 2. JNDI properties from Java :comp/env 3.Java System properties (system.getProperties ()) 4 The configuration of the operating system environment variable 5. RandomValuePropertySource random. * attribute values from the external jars to jar package to look for: priority loading with a profile: 6. Application -{profile}. Properties/yML (with spring.profile) configuration file outside the jar package Application -{profile}. Properties/yML (with spring.profile) 8. Application -{profile}. Properties/yML (without spring.profile) configuration file outside the jar package Application -{profile}.properties/ yML (without spring.profile) configuration file 10.@Configuration annotation @propertysource 11 on class. Through SpringApplication. SetDefaultProperties specify default properties
Principle of Automatic configuration
- When SpringBoot starts, the main configuration class is loaded and the automatic configuration function @enableAutoConfiguration is enabled
- @ EnableAutoConfiguration role: use EnableAutoConfigurationImportSelector to container import components. See the selectImports() method for an implementation:
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes); Obtain the candidate configuration SpringFactoriesLoader. LoadFactoryNames (); Scan meta-INF /spring.factories under the classpath of all JAR packages. The scanning to the contents of these files are packaged into a properties object, from the properties to EnableAutoConfiguration. The class (class name) the value of the class and then add them in the containerCopy the code
Add all the EnableAutoConfiguration values configured in meta-INF/Spring. factories under the classpath to the container.
- Each auto-configuration class performs auto-configuration functions.
@Configuration // indicates that this is a configuration class, similar to a configuration file, that can add components to the container
@EnableConfigurationProperties({HttpProperties.class}) // Enable the ConfigurationProperties function for the specified class
@ ConditionalOnWebApplication (/ / Spring bottom @ conditional comments, according to different conditions, if meet the specified conditions, The configuration in the entire configuration class takes effect (to determine whether the current application is a Web application) type = type.servlet)
@ConditionalOnClass({CharacterEncodingFilter.class}) / / judge the current project to have the class, CharacterEncodingFilter: for SpringMVC in garbled filter
Prefix = "spring.http.encoding", value = {"enabled"}, MatchIfMissing = true / / even if the configuration file is not configured spring. HTTP. Encoding. The enable = true, is also the default effect)
public class HttpEncodingAutoConfiguration {
Copy the code
Depending on the current conditions, to determine whether the configuration class is valid or not, the @bean adds various components to the container, whose values need to be retrieved from properties, each of which is bound to a configuration file. Note:
- @Conditional derived annotations (from the underlying Spring annotation @Conditional) 1. Action: Only if the condition specified by @Conditional is true, can a component be added to the container, and all the contents in the configuration take effect. 2. The automatic configuration class takes effect only under certain conditions: in the configuration file
debug=true
Copy the code
You can print an automatic configuration report on the console to see which automatic configurations are effective and which are not.
conclusion
- SpringBoot launches load a large number of auto-configuration classes.
- Determine whether the automatic configuration classes written by SpringBoot default have the required functionality.
- Determine whether the automatic configuration class configures required components. If not, configure them yourself.
- When you add a component to an auto-configuration class in a container, you get properties from Properties and specify their values in the configuration file.
- XxAutoConfiguration: automatically configures the class and adds components to the container. ===xxProperties: encapsulates the related properties in the configuration file and binds them to the configuration file