First, preface
Research Spring Boot also has a short period of time, recently will study things to share, there will probably be a blog about 10~20, the whole series will be a simple blog system as the basis, because light theory a lot of things are not particularly easy to understand, And if every time through a simple small program can not systematically grasp the knowledge points, so a simple system as a basis to see how to implement a complete system through spring boot. In addition to the basic knowledge points of Spring boot, this series involves the combination of spring boot and database, cache (REDIS), Message Queuing, and multi-instance deployment. Interested students can pay attention to.
Second, Spring boot introduction
Spring boot from the name can be seen, it is based on a framework of spring, so not familiar with spring students still have to learn spring first. Second, Spring boot helps us integrate many common features, making the entire configuration easier. Spring students should know that although spring has been trying to reduce the complexity of the configuration, it is cumbersome to configure a fully available (web) environment, such as the need to configure logs, databases, caches, etc., and then configure Tomcat, Finally, publish the program to the Tomcat directory. Spring boot helps us greatly simplify this process by providing a lot of starter, as long as the corresponding jar package is introduced. For example, we need to integrate Tomcat, just to introduce Tomcat's starter:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId> Spring-boot-starter-tomcat</artifactid></dependency>
Note: Examples of this article are based on Maven, so if you are not familiar with Maven, you can first see how to use, if you are familiar with Gradle, you can also adjust the configuration according to the situation.
We can view the starter provided by spring Boot from the official documentation:
Here I've only intercepted a small subset of the spring boot support cache, batch, MQ, ES, and so on, full list reference official documentation. The rest is not much to explain, followed by an example to explain the entire spring boot feature, we first look at spring boot to implement a web version of Hello world!
Third, Hello world procedure
3.1 Hello World source code
First step: 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 Two: Write the Controller class
Package Com.pandy.blog;import Org.springframework.stereotype.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 three: Write the Startup Class (inbound)
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);} }
Running the main method of the class, and then accessing Http://localhost:8080/hello, you can see the following results:
Are you feeling happy? Without a single line of configuration, you can run a web app directly. But have you ever thought about how this was done? Next, we parse the above code in one line, although the number of lines is not many, but there are a lot of things worth learning and understanding.
3.2 Pom File analysis
We start with the Pom file, only two dependencies are introduced into the pom file. The first one is spring-boot-starter-parent, a friend familiar with Maven should know that Maven can also inherit the configuration from the parent pom file, just like the class. We can look at the spring-boot-starter-parent Pom file, because of the length of the problem, this only look at two parts, other things easier to understand, you can read it yourself. The first part is:
The file inherits another Pom file, spring-boot-dependencies, which actually contains a whole bunch of jars to manage the version of the jar package that spring boot relies on, so you can see It is no longer necessary to specify the version number when the jar is introduced into each component. Another place to explain is the management of the configuration file:
As you can see, by default the files under the/src/main/resources directory are added to the Classpath as resource files, and this place is only for Application*.yml,application*.yaml, Application*.properties three types of files for filtering. What does this filter mean? Everyone who has configured spring MVC should know that when configuring a database, we typically configure the database information in a properties file and then <property name= "Driverclass" in the Spring configuration file Value= "${jdbc.driver}" is introduced in the form of/>, the function of this filter is to replace the configuration file configuration name value pair in the spring configuration file ${xxx} characters when compiling, but this function is not necessary, even if not replaced, Spring can also read to configuration items at run time.
To summarize: The role of spring-boot-starter-parent:
1) version management of the jar package.
2) Filtering of configuration files.
3) Common plug-in management.
In fact, from what analysis can be seen, spring-boot-starter-parent most core function is to manage the spring boot depends on all the jar package. However, there is a clear problem with the way of parent, many companies have their own parent files, and Maven is not able to configure multiple parent. If you don't use spring-boot-starter-parent, what should you do?? In fact, spring boot provides another way to solve this problem by adding the dependent management of spring boot 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> </dependencies></dependencyManagement>
In fact, from the above analysis can be seen, this is also the parent of spring-boot-starter-parent Pom file, and this pom file is mainly managed a lot of jar package version. So after importing this, do not need to do their own version management, the individual starter will import the corresponding jar according to their needs, but the version number by Spring-boot-dependencies Unified management. However, the plugins in Spring-boot-starter-parent are not available, and the default profile filtering function is gone. However, this does not affect, on the one hand these features are not necessary, on the other hand, if necessary, it is easy to add themselves.
3.3 HelloWorld class parsing:
Let's take a look at HelloWorld this class, using spring MVC should know, in fact, this class with spring boot not a half-dime relationship, business code is not anything related to spring, this is spring has been pursuing a principle, very intrusive, This is one of the main reasons for spring's success. This class is related to spring in three annotations, namely @controller, @RequestMapping, @ResponseBody, but these three annotations are also provided by spring MVC. There's not much to do with spring boot, and I'm not going to say that, if it's not clear that you can look at the content of Spring MVC, the basic role of three annotations is as follows:
- Controller: identified as a director, Spring automatically instantiates the class.
- Requestmapping:url mapping.
- Responsebody: Automatically converts the returned result to a JSON string.
3.4 Application Class parsing
Finally we look at application this class, you will find that this class of things less, a total of a line of useful code, namely Springapplication.run (Application.class, args); The function of this method is to load the application class, what's so special about this class application? Can look at, in fact, this class is the only special place is an annotation @springbootapplication, so the operation of spring boot must have a lot of contact with this note, we can look at the source of this note:
@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 {
The main method of the note is not said, you can see that the main is to provide aliases for the above annotations. This note comes with four annotations (@Target (Elementtype.type), @Retention (Retentionpolicy.runtime), @Documented, @Inherited) as you should know, Unfamiliar friends see for themselves how the JDK implements the custom annotations. We explain in detail the following three notes: @SpringBootConfiguration, @EnableAutoConfiguration, @ComponentScan.
First look at the springbootconfiguration, this note is relatively simple, the source code is as follows:
@Target ({elementtype.type}) @Retention (retentionpolicy.runtime) @Documented @configurationpublic @interface Springbootconfiguration {}
This note is only inherited by @configuration and you should be aware that spring provides three ways of configuring: (1) XML file configuration (2) annotation configuration (3) Java class configuration. The @configuration is used to identify a class as a configuration class annotation. Spring 4 is more likely to be configured by Java classes, so spring boot also prefers this type of configuration. And from the source code can be seen, the role of springbootconfiguration is to identify the class as a configuration class.
Next we look at the @enableautoconfiguration annotation, the source of this note is a bit complex, in this do not elaborate, the following article in detail the resolution of the implementation of the way. Here is the function of the annotation, its main function is to implement automatic configuration, what is called automatic configuration? Is that spring boot will do some automatic configuration based on the jar package you introduced, for example, jar,spring boot with hsqldb in Classpath will automatically configure you with a memory database. In this example we can also see that because we have introduced SPRING-MVC, Tomcat and other related jar,spring boot will guess you are a Web project, and then will automatically do some spring MVC configuration, such as the support of static resources, Automatic conversion of returned results to JSON-formatted data support. These are the results 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 look at @componentscan, which is not provided by spring boot, but rather spring-scanned packages or classes, that is, which packages and classes are automatically incorporated into the management of the spring IOC container, and the IOC instantiates the classes based on the configuration.
Now let's summarize the role of the springbootconfiguration annotation:
1) Flag The class as a configuration class.
2) Specify the scanned package to facilitate instance and lifecycle management of the spring IOC container.
3) automatic configuration, through the introduction of the jar package, guess the user's intent to automate the configuration.
Iv. Summary
This article analyzes the spring boot implementation of a web version of Hello World, through this example, we understand the basic operation of spring boot, and through the analysis of each line of code, the principle of spring boot has a general understanding. In general, Spring boot unifies the jar package and then automates the configuration according to our chosen starter, which solves complex dependency management and streamlines configuration, allowing developers to focus more on their business without having to do complicated configuration work. At the same time, Spring boot is a fast, lightweight service that is ideal for micro-service architectures, and this follow-up has the opportunity to share with you and welcome your continued attention.
Spring Boot Combat Progressive interpretation HelloWorld