1. Preface
I have been studying Spring boot for a while. I will organize my research and share it with you recently. There will be about 10 to 20 blogs. The entire series will be based on a simple blog system, because it is not very easy to understand just by talking about theory, and if you can't systematically grasp some knowledge points every time through a simple mini program, so based on a simple system, let's see how to implement a complete system through spring boot. In addition to the basic knowledge points of Spring boot, this series also involves the combination of Spring boot with database, caching (redis), message queues, etc., as well as multi-instance deployment. Interested students can pay attention.
2. Introduction to Spring boot
Spring boot can be seen from the name that it is based on Spring, so students who are not familiar with Spring should learn about Spring first. Secondly, Spring boot helps us integrate many commonly used functions, making the entire configuration simpler. Students who have used Spring should know that although Spring has been working hard to reduce the complexity of configuration, it is still quite troublesome to configure a fully available (web) environment, such as configuring logs, databases, caches, etc., then configuring tomcat, and finally publish the program to the tomcat directory. Spring boot has greatly simplified this process. It provides many starters, just introduce the corresponding jar package. For example, we need to integrate tomcat, just introduce tomcat's starter:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId></dependency>
Note: The examples in this article are all based on Maven, so if you are not familiar with Maven, you can first see how to use it. If you are familiar with gradle, you can also make corresponding adjustments to the configuration according to the situation.
We can view the starter provided by Spring boot from the official documentation:
Here I only intercepted a small part, and you can see that Spring boot supports caching, batch processing, mq, es, etc. For the complete list, refer to the official documentation. I won’t explain much else. I will explain the entire Spring boot function through examples. Let’s first look at Spring boot to implement a web version of Hello World!
3. Hello World Program
3.1 Hello World Source Code
Step 1: Import the jar package
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
Step 2: Write the controller class
package com.pandy.blog;import org.springframework.steretype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import java.util.HashMap;import java.util.Map;@Controllerpublic class HelloWorld { @RequestMapping("/hello") @ResponseBody public Map<String, Object> hello() { Map<String, Object> map = new HashMap<>(); map.put("hello", "world"); return map; }}Step 3: Write the startup class (enter the library)
package com.pandy.blog; import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); }}Run the main method of this class, and then visit http://localhost:8080/hello, and you can see the following results:
Do you feel very happy? If you don't have a single line of configuration, you can run a web application directly. But have you ever thought about how this is achieved after being happy? Next, we parse the above code line by line. Although there are not many lines, there are still many things worth learning and understanding.
3.2 pom file analysis
Let's start with the pom file, which only introduces two dependencies in the pom file. The first one is spring-boot-starter-parent. Friends who are familiar with Maven should know that Maven can also inherit configuration from the parent pom file like the class. We can look at the pom file of spring-boot-starter-parent. Due to space issues, we only look at two parts here. Other things are easier to understand. You can read them yourself. The first part is:
This file inherits another pom file, namely spring-boot-dependencies. This file actually contains a lot of jars, and its function is to uniformly manage the version of the jar package that spring boot depends on. So you can see later that when introducing jars into each component, there is no need to specify the version number. Another point that needs to be explained is the management of configuration files:
As you can see, by default, the files in the /src/main/resources directory will be added to the classpath as resource files. In addition, this place only filters the three files: application*.yml, application*.yaml, and application*.properties. What does this filter mean? Anyone who has configured spring mvc should know that when configuring a database, we usually configure the database information in a properties file, and then introduce it in the spring configuration file through the form of <property name="driverClass" value="${jdbc.driver}" />. The function of this filter is to replace the name value pairs configured in the configuration file with the ${xxx} characters in the spring configuration file during compilation, but this function is not necessary. Even if it is not replaced, Spring can read the configuration items at runtime.
To summarize: The role of spring-boot-starter-parent:
1) JAR package management.
2) Default configuration file management.
3) Common plug-in management.
In fact, from the analysis of what, we can see that the core function of spring-boot-starter-parent is to manage all jar packages that Spring boot depends on. However, there is an obvious problem with the parent method. Many companies have their own parent files, and maven cannot configure multiple parents. What should I do if spring-boot-starter-parent is not used? Do you need to import jar packages one by one? In fact, Spring boot provides another way to solve this problem, which is to add spring boot's dependency management to its own pom file:
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>1.5.9.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </dependency> </
In fact, from the above analysis, we can see that this is also the parent of the spring-boot-starter-parent pom file, and this pom file mainly manages a lot of jar packages. So after importing this, you don’t need to jar one by one to import it. However, in this case, the plug-in in spring-boot-starter-parent will not be used, and the default configuration file replacement function is no longer available. However, this has no effect. On the one hand, these functions are not necessary, and on the other hand, if necessary, it is easy to add them yourself.
3.3 HelloWorld class analysis:
Let’s look at the HelloWorld class. After using Spring mvc, you should know that this class is not related to Spring boot, and the business code does not have anything related to spring. This is also a principle that spring has always adhered to, and it is extremely invasive, which is also a main reason for Spring’s success. There are three annotations related to spring in this class, namely @Controller, @RequestMapping, and @ResponseBody, but these three annotations are also provided by Spring mvc. There is not much connection with Spring boot, so I won't go into details here. If you are not very clear, you can check out the content of Spring MVC. The basic functions of the three annotations are as follows:
3.4 Application class analysis
Finally, let’s look at the Application class, and you will find that there are even fewer things in this class. There is only one line of useful code in total, namely SpringApplication.run(Application.class, args); The function of this method is to load the Application class. So is there anything special about the Application class? You can take a look. In fact, the only special thing about this class is an annotation @SpringBootApplication, so the operation of Spring boot must have many connections with this annotation. We can look at the source code of this annotation:
@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 {I won’t talk about the main method of this annotation. You can see after reading it. It is mainly to provide alias for the above annotations. Everyone should know that the first four annotations (@Target(ElementType.TYPE), @Retention(RetentionPolicy.RUNTIME), @Documented, @Inherited) are mentioned above. Friends who are not familiar with it will take a look at how JDK implements customized annotations. Let's explain the next three annotations in detail: @SpringBootConfiguration, @EnableAutoConfiguration, @ComponentScan.
Let’s take a look at SpringBootConfiguration first. This annotation is relatively simple, and the source code is as follows:
@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Configurationpublic @interface SpringBootConfiguration {}This annotation only inherits @Configuration. Everyone should know that Spring provides three ways of configuration: (1) xml file configuration (2) annotation configuration (3) Java class configuration. @Configuration is an annotation used to identify a class as a configuration class. After Spring 4, configuration is more popular in Java classes, so Spring boot also tends to be in this way. And from the source code, it can be seen that the function of SpringBootConfiguration is to identify the class as a configuration class.
Next, let’s take a look at the @EnableAutoConfiguration annotation. The source code of this annotation is a bit complicated. I won’t go into details here. I will implement it in the later article in detail. Let me talk about the function of this annotation. Its main function is to implement automatic configuration. What is automatic configuration? Spring boot will make some automatic configuration based on the jar package you introduced. For example, if there is a HSQLDB jar in classpath, spring boot will automatically configure an in-memory database for you. In this example, we can also see that because we have introduced Spring-mvc, tomcat and other related jars, spring boot will guess that you are a web project, and then it will automatically do some spring mvc configurations, such as support for static resources, support for automatically converting the returned results to json format data, etc. These are the result of automatic configuration. Students who are familiar with Spring Enable* annotations should be able to understand this annotation more easily, because there are many similar annotations in Spring.
Finally, let’s take a look at @ComponentScan. This annotation is not provided by Spring boot, but is provided by Spring. The packages or classes scanned by Spring, that is, which packages and classes will be automatically included in the management of Spring IoC containers. IoC instantiates these classes according to the configuration.
Now let's summarize the function of the SpringBootConfiguration annotation:
1) Mark that this class is a configuration class.
2) Specify the scanned package to facilitate Spring IoC containers to manage their instance and life cycles.
3) Automatic configuration, and use the introduced jar package to guess the user's intention to automatically configure.
4. Summary
This article analyzes a web version of Hello World implemented by Spring boot in detail. Through this example, we understand the basic operations of Spring boot, and through the analysis of the code on each line, we have a rough understanding of the principles of Spring boot. Overall, Spring boot manages jar packages uniformly, and then automatically configures them according to the starter we choose. This way, solves complex dependency management and streamlines configuration, so that developers can focus more on their business without having to do very complicated configuration work. At the same time, Spring boot's fast and lightweight service is also very suitable for microservice architecture. I will share this with you if you have the opportunity to follow up. Welcome to continue to follow.