Introduction to SpringBoot
1. What is SpringBoot
Background: Spring development is tedious, with many configuration files, complex deployment process, and difficulty in integrating third-party frameworks. This reduces development efficiency
SpringBoot is a framework that simplifies the creation and development of Spring applications
Integrating the entire Spring technology stack, it is a one-stop solution for JavaEE development
2.为什么使用SpringBoot
Advantages:
- Spring projects can be quickly architected and integrated with mainstream frameworks
- Built-in Servlet container, no need to manually deploy the WAR package
- Starter is used to manage dependencies and version control
- Lots of automatic configuration to simplify development
- Provides run-time monitoring of a quasi-production environment
- No XML files are required
Second, the first SpringBoot program
1. Procedure
Steps:
1.1 Create a JAR project for Maven
Traditional applications need to create web projects, then break the application into a WAR package, and then deploy it in a container
SpringBoot, on the other hand, requires only a JAR package with Tomcat built in
1.2 Importing SpringBoot Dependencies
<? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > The < modelVersion > 4.0.0 < / modelVersion > < groupId > com. Ly < / groupId > < artifactId > springboot01 - the helloworld < / artifactId > < version > 1.0 - the SNAPSHOT < / version > < the parent > < groupId > org. Springframework. Boot < / groupId > The < artifactId > spring - the boot - starter - parent < / artifactId > < version > 2.1.9. RELEASE < / version > < / parent > <name>springboot01-helloworld</name> <! -- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> < project. Build. SourceEncoding > utf-8 < / project. Build. SourceEncoding > < maven.com piler. Source > 1.8 < / maven.com piler source > </properties> <dependencies> <dependency> <groupId> </groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> </build></project>Copy the code
1.3 create a Controller
package com.ly.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * Author: LuYi * Date: 2019/10/27 11:05 * Description: */ @controllerPublic Class HelloController {@requestMapping ("/hello") @responseBody public String Hello (){return "Hello World"; }}Copy the code
1.4 Creating a Startup Class
package com.ly; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Author: LuYi * Date: 2019/10/27 11:05 * Description: Using the @ SpringBootApplication class mark into SpringBoot application * / @ SpringBootApplicationpublic class App {public static void main (String [] args) { SpringApplication.run(App.class, args); }}Copy the code
The package in which the @SpringBootApplication annotation resides and its subpackages are scanned by default, and can also be specified using the @ComponentScan(” com.ly.Controller “) annotation
1.5 packaging
<! <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins></build>Copy the code
To add the plug-in, make the application into an executable JAR package by executing the java-jar jar file
2. Analyze the HelloWorld
2.1 POM file
- The parent project
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> < version > 2.1.9. RELEASE < / version > < / parent >Copy the code
- Parent project parent project: used to manage versions dependent on SpringBoot applications for version control
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> < version > 2.1.9. RELEASE < / version > < relativePath >.. /.. /spring-boot-dependencies</relativePath></parent>Copy the code
- Dependencies: Specify dependencies through the starter
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>
Copy the code
- SpringBoot provides many starters for different application scenarios. When these starters are introduced in a project, the dependencies for the corresponding scenario are imported
2.2 start the class
@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@SpringBootConfiguration@EnableAutoCo nfiguration@ComponentScan( excludeFilters = {@Filter( type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class}), @Filter( type = FilterType.CUSTOM, classes = {AutoConfigurationExcludeFilter.class})})Copy the code
- @SpringBootApplication
- Marked on a class, it indicates that the class is the boot class of SpringBoot. The SpringBoot application is started using the Main method of the class
- @SpringBootConfiguration
- Marked on a class to indicate that this class is the SpringBoot configuration class
- Hierarchy: SpringBootConfiguration — >@Configuration — >@Component
@Configuration: Annotated on a class to indicate that this class is a Spring Configuration class, equivalent to an XML Configuration file
- @EnableAutoConfiguration
- The automatic configuration function is enabled, simplifying complex configurations
- SpringBoot starts with the values specified by EnableAutoConfiguration in/meta-INF/Spring. factories and adds these values to the container as auto-configuration classes that do a lot of the configuration for us.
- @ComponentScan
- Annotated on a class, specifying the package and its subpackages to scan
Quickly create a SpringBoot project
1. Introduction
Use Spring Initializer to quickly build a SpringBoot project
2. Basic operations
- Pom files and main program classes automatically generated, directly write business logic
- The directory structure of the Resources folder
| - static storage static resources, such as js, CSS, images | deposit - template template engine, such as a freemarker, thymeleaf | - application. The properties SpringBoot application configuration file, You can modify the default SettingsCopy the code
4. Configuration files
1. Introduction
There are two default global configuration files for SpringBoot:
- application.properties
- application.yml
The file name is fixed and stored in the classpath:/ or classpath:/config/ directory
You can modify the default Spring Boot configuration. For details, see docs. Spring-boot.
Note: the configuration of SpringBoot2.0 differs from 1.0, and some configuration items have been removed
2. Use YAML
2.1 introduction
YAML is not a markup language. YAML is specifically designed to write configuration files. It is data-centric, powerful and better suited to configuration files than XML and Properties
YAML files are named after. Yml or. YAML
2.2 application. Yml
Servlet: context-path: /springboot03/ server: port: 8081 #Copy the code
2.3 Grammar Rules
- Case sensitivity
- Use indentation to indicate hierarchy
- The Tab key is not allowed for indentation
- The number of indented Spaces is not important, but should be aligned to the left of the corresponding level
- # comment
2.4 Basic Usage
YAML supports three types of data structures:
- Literal: A single, non-divisible value (string, number, Boolean value)
- Object: a collection of key-value pairs
- Array: A set of values arranged in order
Use of three data structures:
1. Literals: common values such as numbers, strings, booleans
Number: 12.5 STR: helloname: 'Tom cruise' # 'Tom \n cruise' # does not escape special characters result in: Tom newline cruisename: "Tom \n cruise" # Escapes special characters and outputs them as normal characters, resulting in Tom \n cruiseCopy the code
- Object, also known as a mapping Map, contains attributes and values
{name: Tom, age: 20, sex: male} user: name: Tom, age: 20 sex: male}Copy the code
- Array, such as List, Set, etc
Name: {Tom,jack, Alice}Copy the code
3. Inject values for properties
Inject values for properties in a class by loading a configuration file
3.1 write application. Yml
User: username: admin Age: 21 Status: true birthday: 2019/2/14 Address: Province City: Harbin Lists: - list1 - list2 - list3 maps: {k1: v1,k2: v2}Copy the code
3.2 Creating an Entity Class
User
package com.luyi.bean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.Date; import java.util.List; import java.util.Map; /** * Author: LuYi * Date: 2019/10/27 13:49 * Description: /// The current class must be added to the container @component // By default, the global configuration file is read to get the value, @configurationProperties (value = "user") Public class user {private String username; private Integer age; private Boolean status; private Date birthday; private Address address; private List<String> lists; private Map<String, Object> maps; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Boolean getStatus() { return status; } public void setStatus(Boolean status) { this.status = status; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public List<String> getLists() { return lists; } public void setLists(List<String> lists) { this.lists = lists; } public Map<String, Object> getMaps() { return maps; } public void setMaps(Map<String, Object> maps) { this.maps = maps; } @Override public String toString() { return "User{" + "username='" + username + '\'' + ", age=" + age + ", status=" + status + ", birthday=" + birthday + ", address=" + address + ", lists=" + lists + ", maps=" + maps + '}'; }}Copy the code
Address
package com.luyi.bean; /** * Author: LuYi * Date: 2019/10/27 13:50 * Description: Description */public class Address {private String type; private String city; public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return "Address{" + "province='" + province + '\'' + ", city='" + city + '\'' + '}'; }}Copy the code
3.3 test
package com.luyi.springboot03config; import com.luyi.bean.User; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTestclass Springboot03ConfigApplicationTests { @Autowired private User user; @Test void contextLoads() { System.out.println(user); }}Copy the code
3.4 (Optional) Adding a Configuration File Processor Dependency
<! -- Configuration file processor, automatically generate metadata information, <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional></dependency>Copy the code
3.5 Using the Properties Configuration file
User. The username = aliceuser. Age = 22. The user status = falseuser. Birthday = 2019/10/27 user. Address. Province = user in heilongjiang province. The address. The Harbin city = us er.lists=list1,list2,list3user.maps.k1=v1user.maps.k2=v2Copy the code
Note: The default utF-8 encoding is used in IDEA, and the default ASCII encoding is used in properties files. Therefore, garbled characters will appear, which can be resolved by checking
Priority: properties > yML
3.6 Use the @value annotation to inject values
@Value("${user.username}")private String username; @Value("${user.age}")private Integer age; @Value("${user.status}")private Boolean status; @Value("${user.birthday}")private Date birthday; // @value does not support complex type encapsulation private Address Address; @Value("${user.lists}")private List<String> lists; private Map<String, Object> maps;Copy the code
ConfigurationProperties:
- The former can only be injected single-value, while the latter can be injected in batches
- The former does not support encapsulation for complex types, while the latter does
4. Configure multiple environments
You can provide different configuration information for different environments, such as development environment, test environment, and production environment
Two ways:
- Create multiple properties files
- Define yML document blocks
4.1 Create multiple Properties files
Steps:
1. Create properties files for different environments
The file name must be in the aplication-xxx.properties format
application-dev.properties
server.port=9991
Copy the code
application-test.properties
server.port=9992
Copy the code
application-prod.properties
server.port=9993
Copy the code
2. Specify the configuration to be activated in application.properties
# Specify the configuration spring.profiles. Active =prod to be activatedCopy the code
4.2 Defining YML document blocks
1. Use three dashes to define multiple document blocks in YML
spring: profiles: devserver: port: 9991---spring: profiles: testserver: port: 9992---spring: profiles: prodserver: port: 9993
Copy the code
2. Specify the environment to activate in the first document block
spring: profiles: active: test---
Copy the code
5. Load the external configuration file
5.1 Loading the Properties file
Question: @ConfigurationProperties reads values from the global configuration file by default. What if you want to get values from the custom properties file?
Solution: Load the external properties file using the @propertysource annotation
/ / the current class must be added to the container @ Component / / load the external properties file @ PropertySource ({" classpath: user. The properties "}) / / read global configuration file by default value, @configurationProperties (value = "user")public class user {Copy the code
5.2 Loading the Spring Configuration File
Question: What if I have information that NEEDS to be written to an XML file and want to load the XML file
Solution: Load the external configuration file using @importResource
5.3 Adding components using Annotations
It is recommended to add components, @Configuration and @Beans, to the Spring container using full annotations
/** * Author: LuYi * Date: 2019/10/28 14:49 * Description: Configurationpublic Class SpringConfig {// The method is used to add components to the container. The return value of the method is added to the container. @bean public Address Address() {Address Address = new Address(); Address. SetProvince (" shandong "); Address. SetCity (" sunshine "); return address; }}Copy the code
Principle of SpringBoot automatic configuration
1. Execute the process
1. When SpringBoot starts, the main configuration class is loaded, and the @enableAutoConfiguration command is used to enable automatic configuration
2. The usage of @ @ EnableAutoConfiguration Import ({AutoConfigurationImportSelector. Class}) to add some components in the container (to be automatic configuration class)
See AutoConfigurationImportSelector selectImports method in class, and then click getAutoConfigurationEntry method of ` getCandidateConfigurations method
Through getCandidateConfigurations loadFactoryNames method of load to SpringFactory,
Use the classLoader to load the meta-INF /spring.factories configuration Obtain the value of EnableAutoConfiguration (spring-boot-autoconfigure-2.1.9.release.jar) from the configuration.
Add these auto-configuration classes (xxxAutoConfiguration) to the container
3. Use the automatic configuration function.
2. Principle analysis
HttpEncodingAutoConfiguration, for example, is used in the web. In the XML configuration CharacterEncodingFilter filter
// Enable the ConfigurationProperties function of the HttpProperties class. It uses the Configuration file to inject values for properties. And add it to the container @ EnableConfigurationProperties ({HttpProperties. Class}) / / to come into force when the application is a web application @ ConditionalOnWebApplication (type = The SERVLET) / / must contain only effective CharacterEncodingFilter class @ ConditionalOnClass ({CharacterEncodingFilter. Class}) / / if there is a spring configuration file. The HTTP. Encoding Takes effect. Otherwise, the configuration does not take effect. ConditionalOnProperty(prefix = "spring.http.encoding", value = {"enabled"}, matchIfMissing = true)public class HttpEncodingAutoConfiguration { private final Encoding properties; / / in the container HttpProperties into public HttpEncodingAutoConfiguration (HttpProperties properties) {enclosing the properties = properties.getEncoding(); } // Add the returned filter to the container, ConditionalOnMissingBean public CharacterEncodingFilter () {ConditionalOnMissingBean CharacterEncodingFilter () CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter(); filter.setEncoding(this.properties.getCharset().name()); filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.En coding.Type.REQUEST)); filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.E ncoding.Type.RESPONSE)); return filter; } // Get the specified value from the configuration file, @configurationProperties (prefix = "spring.http") Public Class HttpProperties {private Charset Charset; private Boolean force; private Boolean forceRequest; private Boolean forceResponse; private Map<Locale, Charset> mapping;Copy the code
Note:
- Based on the current situation, determine whether the configuration class is produced. If the conditions are not met, the automatic configuration does not take effect
- The properties of the automatic configuration class xxAutoConfiguration are obtained from the corresponding xxProperties class
- The information in the xxProperties class is bound by injection of a configuration file, through which you can specify the value of the property
3. Summary
- SpringBoot loads a large number of auto-configuration classes at startup
- Components are added to the container through automatic configuration
- Many functions are automated through these components to simplify configuration
You can enable the debug mode to view the matching status of automatic configuration classes
Debug =trueCopy the code
Web development
1. Introduction
Steps for developing Web applications using SpringBoot:
1. Create a SpringBoot project and add the corresponding starter
2. Specify a few necessary configurations in the configuration file
3. Write business code
WebMvcAutoConfiguration, an automatic configuration class for Web development
2. Static resource mapping
2.1 Location of Static Resources
See WebMvcAutoConfiguration – > addResourceHandlers () – > getStaticLocations () – > staticLocations
Default location for static resources
"classpath:/META-INF/resources/","classpath:/resources/", "classpath:/static/", "classpath:/public/"
Copy the code
Static resources can be accessed through the folder above
You can also specify access locations in the configuration file
Spring.resources. static-locations=classpath:/public; spring.resources.static-locations=classpath:/publicCopy the code
2.2 welcome page
See WebMvcAutoConfiguration – > welcomePageHandlerMapping () – > getWelcomePage ()
Place the index.html page in any of the static resources folders
2.3 Website Icon
See WebMvcAutoConfiguration – > Inner class FaviconConfiguration – >faviconHandlerMapping
Place favicon.ico in any folder of a static resource
Spring Boot interview questions, and Spring Boot learning notes complete tutorial concerns: Kirin bug, get.