If you want speed, you will not reach it. If you want speed, you will reach it!
hello, hello, I've met you again. Today is February 1, 2020. On the eighth day of the lunar new year, the Spring Festival will soon be over. The new type of coronavirus pneumonia has become the theme of the Spring Festival in 2020. I'm in awe of life. I hope I can survive. Come on!
To put it bluntly, I have been studying java framework recently. At this time, the most popular Spring Boot, learning framework and reading books are indispensable? out! B station video starts!
I've seen section 16. What should I write about my habitual feeling? I'll share it with you!
1, Getting started with Spring Boot
1. Introduction to Spring Boot
(1) A framework to simplify spring application development;
(2) A big integration of spring technology stack;
(3) One stop solution developed by J2EE;
2. Microservice
In 2014, martin fowler put forward the word "micro service" and wrote a blog, officially entering the era of micro service.
Microservices: architecture style (service miniaturization)
An application should be a group of small services, which can be exchanged through HTTP;
Single application: ALL IN ONE
Microservices: each functional element is a software unit that can be replaced and upgraded independently;
[refer to the microservice document for details]
3. Environmental preparation
Environmental constraints
– JDK1.8: Spring Boot recommends jdk1.7 and above; jdk1.8.0_
– Maven 3. X: Maven 3.3 and above; Apache Maven 3.3.9
–IntelliJIDEA2017: IntelliJ IDEA 2017.2.2 x64,STS
–SpringBoot 1.5.9.RELEASE: 1.5.9;
4,Spring Boot HelloWorld
(1) maven configuration
Add the profiles tab to maven's settings.xml configuration file
<profile> <id>jdk-1.8</id> <activation> <activeByDefault>true</activeByDefault> <jdk>1.8</jdk> </activation> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion> </properties> </profile>
(2) Import spring boot related dependencies
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
(3) Write a main program; start the Spring Boot application
/** * @SpringBootApplication To mark a main program class, indicating that this is a Spring Boot application */ @SpringBootApplication public class HelloWorldMainApplication { public static void main(String[] args) { // Spring application starts SpringApplication.run(HelloWorldMainApplication.class,args); } }
(4) Write related Controller and Service
@Controller public class HelloController { @ResponseBody @RequestMapping("/hello") public String hello(){ return "Hello World!"; } }
(5) Run main program test
(6) Simplified deployment
· <!-- This plug-in can package the application into an executable jar Package;--> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
Make this application into a jar package and execute it directly with the command of Java jar
5. Hello World exploration
(1) POM file
Parent project
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent> His parent project is <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>1.5.9.RELEASE</version> <relativePath>../../spring-boot-dependencies</relativePath> </parent> He's in charge Spring Boot All dependent versions in the application;
starter
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
Spring boot starter: spring boot scene starter, which helps us import the components that the web module depends on for normal operation;
Spring Boot extracts all the functional scenarios and makes them into starters one by one. It only needs to import all the dependencies of these starter related scenarios into the project. Import the initiator of any scene with whatever function you want.
(2) Main program class
/** * @SpringBootApplication To mark a main program class, indicating that this is a Spring Boot application */ @SpringBootApplication public class HelloWorldMainApplication { public static void main(String[] args) { // Spring application starts SpringApplication.run(HelloWorldMainApplication.class,args); } }
@**SpringBootApplication * *: the Spring Boot application annotation indicates on a class that this class is the main configuration class of SpringBoot. SpringBoot should run the main method of this class to start the SpringBoot application;
@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 { }
@**Springbootconfiguration * *: configuration class of spring boot;
Marked on a class, indicating that it is a Spring Boot configuration class;
@**Configuration * *: this annotation is marked on the configuration class;
Configuration class ---- configuration file; configuration class is also a component in the container; @Component
@**Enable autoconfiguration * *: enable autoconfiguration;
What we need to configure before, Spring Boot helps us to configure automatically; @ * * EnableAutoConfiguration * * tells Spring Boot to enable the auto configuration function, so that the auto configuration can take effect;
@AutoConfigurationPackage @Import(EnableAutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration { }
@**AutoConfigurationPackage * *: autoconfiguration package
@**Import**(AutoConfigurationPackages.Registrar.class):
Spring's underlying annotation @ Import imports a component to the container. The imported component is AutoConfigurationPackages.Registrar.class;
==Scan the package of the main configuration class (the class marked by @SpringBootApplication) and all the components in all the sub packages below to the Spring container==
@**Import**(EnableAutoConfigurationImportSelector.class);
Import components to container?
* * EnableAutoConfigurationImportSelector * *: the selector of which components to import;
Return all components that need to be imported in the form of full class names; these components will be added to the container;
Many auto configuration classes (xxxAutoConfiguration) will be imported into the container, that is, all the components required for the scene will be imported into the container, and these components will be configured properly;! [auto configuration class] (images / Sogou screenshot 20180129224104.png)
With the automatic configuration class, we can write configuration injection function components manually;
SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,classLoader);
==Spring Boot gets the values specified by EnableAutoConfiguration from META-INF/spring.factories in the classpath when it starts, imports these values into the container as auto configuration classes, and the auto configuration classes take effect to help us with auto configuration; = = we need to configure things ourselves before, and auto configuration classes help us;
The whole integration solution and automatic configuration of J2EE are in spring boot autoconfigure-1.5.9.release.jar;
6. Using Spring Initializer to quickly create a Spring Boot project
(1) IDEA: using Spring Initializer to create projects quickly
IDE supports using Spring's project creation wizard to quickly create a Spring Boot project;
Select the modules we need; the wizard will create the Spring Boot project online;
Spring Boot project generated by default;
-The main program has been generated, we only need our own logic
-Directory structure in resources folder
- static: save all static resources; js css images;
- templates: save all template pages; (the default jar package of Spring Boot uses embedded Tomcat, and JSP pages are not supported by default); you can use template engine (freemarker, thmeleaf);
- application.properties: configuration file of Spring Boot application; some default settings can be modified;
(2) STS uses Spring Starter Project to create projects quickly
2, Profile
1. Profile introduction
Spring boot uses a global configuration file with a fixed name;
- application.properties
- application.yml
The function of configuration file: modify the default value of spring boot automatic configuration; spring boot automatically configures for us at the bottom;
YAML(YAML Ain't Markup Language)
YAML A Markup Language: A Markup Language
YAML isn't Markup Language: not a markup language;
Markup Language:
Previous configuration files mostly use the * * xxxx.xml * * file;
YAML: * * data centric * *, more suitable for configuration files than json, xml, etc;
YAML: Configuration Example
server: port: 8081
2. YAML syntax:
(1) Basic grammar
k: (space) v: indicates a pair of key value pairs (space must have);
Use the indentation of * * space * * to control the hierarchical relationship; as long as the left aligned column data is the same level
server: port: 8081 path: /hello
Attributes and values are also case sensitive;
(2) How to write values
- Literal: normal value (number, string, Boolean)
k: v: write directly;
By default, strings do not need single or double quotation marks;
": double quotation marks; special characters in strings will not be escaped; special characters will be used as the meaning they want to express
name: "zhangsan \n lisi": output; zhangsan line feed lisi
': single quotation mark; it will escape special characters, which are only common string data
name: 'zhangsan \n lisi': output; zhangsan \n lisi
- Object, Map (property and value) (key value pair):
k: v: Write the relationship between the properties and values of the object on the next line; note indenting
Object or k: v Way
friends: lastName: zhangsan age: 20
- Array (List, Set):
Represents an element in an array with a - value
pets: - cat - dog - pig
3. Profile value injection
(1) yml profile
person: lastName: hello age: 18 boss: false birth: 2017/12/12 maps: {k1: v1,k2: 12} lists: - lisi - zhaoliu dog: name: puppy age: 12
(2)javaBean:
/** * Map the value of each property configured in the configuration file to this component * @ConfigurationProperties: Tell SpringBoot to bind all the properties in this class to the relevant configuration in the configuration file; * prefix = "person": Which of the following attributes in the configuration file is mapped one by one * * Only when this component is a component in the container can the @ ConfigurationProperties function provided by the container be enabled; * */ @Component @ConfigurationProperties(prefix = "person") public class Person { private String lastName; private Integer age; private Boolean boss; private Date birth; private Map<String,Object> maps; private List<Object> lists; private Dog dog;
We can import the profile processor and write the configuration later
<!--When importing the profile processor, you will be prompted when binding the profile--> <dependency> groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
(3) Comparison between @ Value get Value and @ ConfigurationProperties get Value
Whether the configuration file yml or properties can get values;
If so, we just need to get a Value in the configuration file in a certain business logic, and use @ Value;
If we specially write a javaBean to map with the configuration file, we will directly use @ ConfigurationProperties;
(4) Profile injection value data verification
@Component @ConfigurationProperties(prefix = "person") @Validated public class Person { /** * <bean class="Person"> * <property name="lastName" value="Literal amount / ${key} gets value from environment variable and configuration file / {spiel} "> < property > * <bean/> */ //lastName must be in mailbox format @Email //@Value("${person.last-name}") private String lastName; //@Value("#{11*2}") private Integer age; //@Value("true") private Boolean boss; private Date birth; private Map<String,Object> maps; private List<Object> lists; private Dog dog;
(5)@PropertySource&@ImportResource&@Bean
@**PropertySource * *: load the specified configuration file;
/** * Map the value of each property configured in the configuration file to this component * @ConfigurationProperties: Tell SpringBoot to bind all the properties in this class to the relevant configuration in the configuration file; * prefix = "person": Which of the following attributes in the configuration file is mapped one by one * * Only when this component is a component in the container can the @ ConfigurationProperties function provided by the container be enabled; * @ConfigurationProperties(prefix = "person")Get the value from the global configuration file by default; * */ @PropertySource(value = {"classpath:person.properties"}) @Component @ConfigurationProperties(prefix = "person") //@Validated public class Person { /** * <bean class="Person"> * <property name="lastName" value="Literal amount / ${key} gets value from environment variable and configuration file / {spiel} "> < property > * <bean/> */ //lastName must be in mailbox format // @Email //@Value("${person.last-name}") private String lastName; //@Value("#{11*2}") private Integer age; //@Value("true") private Boolean boss;
@**ImportResource * *: import the Spring configuration file to make the content in the configuration file effective;
There is no Spring configuration file in Spring Boot, and the configuration file we wrote ourselves cannot be recognized automatically;
To make the Spring configuration file effective, load it in; @ * * ImportResource * * is marked on a configuration class
@ImportResource(locations = {"classpath:beans.xml"}) Import Spring's configuration file for it to take effect
Don't write Spring's configuration file
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean> </beans>
SpringBoot recommends adding components to containers; full annotation is recommended
- Configuration class * * @ configuration * * ------ > spring configuration file
- Use * * @ Bean * * to add components to the container
/** * @Configuration: Indicates that the current class is a configuration class; that is, to replace the previous Spring configuration file * * Add components with < bean > < bean / > tag in configuration file * */ @Configuration public class MyAppConfig { //Add the return value of the method to the container; the default id of this component in the container is the method name @Bean public HelloService helloService02(){ System.out.println("Configuration class@Bean Added components to container..."); return new HelloService(); } }
4. Placeholder for profile
(1) Random number
${random.value},${random.int},${random.long} ${random.int(10)},${random.int[1024,65536]}
(2) Placeholder gets the value configured before. If not, use: to specify the default value
person.last-name=Zhang San ${random.uuid} person.age=${random.int} person.birth=2017/12/15 person.boss=false person.maps.k1=v1 person.maps.k2=14 person.lists=a,b,c person.dog.name=${person.hello:hello}_dog person.dog.age=15
5,Profile
(1) Multiple Profile files
When we write the main configuration file, the file name can be application-{profile}.properties/yml
The configuration of application.properties is used by default;
(2) yml supports multi document block mode
server: port: 8081 spring: profiles: active: prod --- server: port: 8083 spring: profiles: dev --- server: port: 8084 spring: profiles: prod #Specify which environment to belong to
(3) Activate the specified profile
- Specify spring.profiles.active=dev in the configuration file
- Command line:
java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev;
You can configure the incoming command line parameters directly during the test
- Virtual machine parameters;
-Dspring.profiles.active=dev
6. Profile load location
springboot will scan the application.properties or application.yml file in the following location as the default configuration file of Spring boot
–file:./config/
–file:./
–classpath:/config/
–classpath:/
The priority is from high to the bottom. The high priority configuration will cover the low priority configuration;
Spring boot will load the main configuration files from all four locations; * * complementary configuration * *;
==We can also change the default configuration file location through spring.config.location==
**After the project is packaged, we can use the form of command-line parameters to specify the new location of the configuration file when starting the project; the specified configuration file and the default loaded configuration files work together to form a complementary configuration**
java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --spring.config.location=G:/application.properties
7. External configuration load order
**==SpringBoot can also load configurations from the following locations; the priority is from high to low; high priority configurations cover low priority configurations, and all configurations will form complementary configurations==**
**1. Command line arguments**
All configurations can be specified on the command line
java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --server.port=8087 --server.context-path=/abc
Multiple configurations are separated by spaces; -- configuration item = value
2. JNDI attribute from java:comp/env
3. Java system properties (System.getProperties())
4. Operating system environment variables
5. random. * property value of RandomValuePropertySource configuration
==**Search from jar package to jar package**==
==**Priority loading with profile**==
**6. application-{profile}.properties or application.yml (with spring.profile) configuration file outside the jar package**
**7. application-{profile}.properties or application.yml (with spring.profile) configuration file inside the jar package**
==**Then load without profile**==
**8. application.properties or application.yml (without spring.profile) configuration file outside the jar package**
**9. application.properties or application.yml (without spring.profile) configuration file inside the jar package**
10. @ PropertySource on @ Configuration annotation class
11. Default properties specified by SpringApplication.setDefaultProperties
All supported configuration loading sources;
8. Auto configuration principle
What can a configuration file write? How do you write it? Automatic configuration principle;
[property reference that can be configured by configuration file]
(1) When SpringBoot starts, the main configuration class is loaded, and the auto configuration function is enabled = = @ EnableAutoConfiguration==
(2) @ EnableAutoConfiguration role:
- Use EnableAutoConfigurationImportSelector to import some components into the container?
- You can view the contents of the selectImports() method;
- List < string > configurations = getcandidate configurations (annotation metadata, attributes); get candidate configurations
SpringFactoriesLoader.loadFactoryNames() Scan META-INF/spring.factories under all jar package Classpaths Wrap the contents of the scanned files into properties objects Get the value of EnableAutoConfiguration.class class (class name) from properties and add them to the container
Add all the value of EnableAutoConfiguration configured in META-INF/spring.factories under the classpath to the container;
Every such xxxAutoConfiguration class is a component in the container, which is added to the container, and used for automatic configuration;
(3) Each auto configuration class can be configured automatically;
(4) Take * * HttpEncodingAutoConfiguration * * as an example to explain the principle of autoconfiguration:
@Configuration //Indicates that this is a configuration class. Like the previously written configuration file, components can also be added to the container @EnableConfigurationProperties(HttpEncodingProperties.class)//Start the ConfigurationProperties function of the specified class; bind the corresponding value in the configuration file with HttpEncodingProperties; and add HttpEncodingProperties to the IOC container @ConditionalOnWebApplication //spring's underlying @ Conditional annotation. According to different conditions, if the specified conditions are met, the configuration in the whole configuration class will be invalid. Judge whether the current application is a web class. If so, the current configuration class will take effect @ConditionalOnClass(CharacterEncodingFilter.class) //Judge whether the current project has this class CharacterEncodingFilter; SpringMVC Filter to solve random code in; @ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true) //Determine whether a configuration spring.http.encoding.enabled exists in the configuration file; if not, it is also true //Even if pring.http.encoding.enabled=true is not configured in our configuration file, it will take effect by default; public class HttpEncodingAutoConfiguration { //Already mapped to the springboot configuration file private final HttpEncodingProperties properties; //In the case of only one parameter 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. Some values of this component need to be returned from properties @ConditionalOnEncodingFilter(CharacterEncodingFilter.class)//Judge the container does not have this component? 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; } }
According to the current different conditions, determine whether the configuration class is effective?
Once the configuration class takes effect, it will add various components to the container. The properties of these components are obtained from the corresponding properties class, and each property in these classes is bound to the configuration file;
(5) All the properties that can be configured in the configuration file are encapsulated in the xxxproperties class. The configuration file can refer to the property class corresponding to a function if it can be configured
@ConfigurationProperties(prefix = "spring.http.encoding") //Get the specified value and bean property from the configuration file to bind public class HttpEncodingProperties { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
* * the essence of * * *
- Spring boot will load a large number of auto configuration classes
- Let's see if the function we need has the auto configuration class written by springboot by default;
- Let's see what components are configured in this auto configuration class (as long as we have components to use, we don't need to configure them again)
- When adding components to the container's auto configuration class, some properties will be automatically obtained from the properties class. We can specify the values of these properties in the configuration file;
Xxxautoconfiguration: autoconfiguration class;
Add components to the container
xxxxProperties: encapsulates the related properties in the configuration file;
9, details
@Conditional derived annotation (Spring annotation version's native @ conditional function)
Function: only when the conditions specified by @ Conditional are valid can components be added to the container and all contents in the configuration take effect;
@Conditional extension annotation | Function (judge whether the current specified conditions are met) |
@ConditionalOnJava | Whether the java version of the system meets the requirements |
@ConditionalOnBean | The specified Bean exists in the container |
@ConditionalOnMissingBean | The specified Bean does not exist in the container |
@ConditionalOnExpression | Meet the SpEL expression specification |
@ConditionalOnClass | There are specified classes in the system |
@ConditionalOnMissingClass | No class specified in the system |
@ConditionalOnSingleCandidate | There is only one specified Bean in the container, or this Bean is the preferred Bean |
@ConditionalOnProperty | Whether the specified property in the system has the specified value |
@ConditionalOnResource | Whether the specified resource file exists under the classpath |
@ConditionalOnWebApplication | web environment at present |
@ConditionalOnNotWebApplication | This is not a web environment |
@ConditionalOnJndi | Specified item exists in JNDI |
The auto configuration class can only take effect under certain conditions;
**We can enable the debug=true property; to let the console print the auto configuration report = = * *, so that we can easily know which auto configuration classes are effective;
========================= AUTO-CONFIGURATION REPORT ========================= Positive matches:(Auto configuration class enabled) ----------------- DispatcherServletAutoConfiguration matched: - @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition) - @ConditionalOnWebApplication (required) found StandardServletEnvironment (OnWebApplicationCondition) Negative matches:(No startup, no matching successful autoconfig class) ----------------- ActiveMQAutoConfiguration: Did not match: - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition) AopAutoConfiguration: Did not match: - @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice' (OnClassCondition)