Why do we need SpringBoot?

Author | A Wen, Editor-in-Chief | Guo Rui

图 | CSDN Download from Oriental IC

Selling | CSDN (ID: CSDNnews)

The generation of any advanced technology is not out of thin air, and SpringBoot is no exception. SpringBoot is based on Spring. As we all know, Spring is a lightweight container that is widely used in Java EE projects, but Spring ’s complicated, cumbersome and bloated XML configuration configuration makes developers very painful in the actual use process, especially with When other third-party tools are integrated, such as Mybatis, it will make the configuration file very complicated and repeated.

For example, let's look at a section of Spring configuration:

The picture above is a section of configuration database and transaction management and Mybatis configuration. We found that there are only a lot of configuration files. Of course, this is not the most complicated. On this basis, SpringBoot was born.

The emergence of SpringBoot has brought new automation configuration solutions to developers, enabling developers to quickly create independent production applications based on Spring based on SpringBoot. SpringBoot provides default automatic configuration solutions for some commonly used third-party libraries. This allows developers to run complete JavaEE applications with very little Spring configuration. Because of its out-of-the-box features and service monitoring solutions, it also comes with a web server and integrates with Spring's other mainstream service management frameworks such as Spring Cloud and kubernetes and other technologies, allowing developers to quickly implement microservices and services The most important thing is that you do not need to configure XML at all, which is really cool.

So, how to get started with Spring Boot? This article will take you through.

Small scale chopper

First, we create a SpringBoot project. There are many ways to create SpringBoot. Here, taking IDEA Enterprise Edition as an example, we choose Spring initalizr and then create a project.

After creating the project, we open pom.xml and we can see this configuration:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

spring-boot-starter-parent is a special starter, which provides some maven default configuration, and also provides dependency-management, so that developers do not have to enter the version number when introducing other dependencies, which is convenient for dependency management.

There are many starters provided by SpringBoot. These starters need to provide automatic configuration for third-party libraries. If we want to configure a web project, we can add them in maven:

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

At the entrance of the project we can see a DemoApplication, which is the entrance of the entire Spring Boot:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class);


    }

}

The @SpringBootApplication annotation is equal to the following annotation, which means to enable automatic configuration and automatic package scanning:

@EnableAutoConfiguration
@ComponentScan

ComponentScan will scan @Service, @Repository, @Component, @Controller, @RestController and the classes annotated with @Configuration, but for convenience, we usually add @SpringBootApplication directly to the entrance.

In the IDE, we can run SpringBoot by running the DemoApplication class. At this time, the following message will appear in the terminal. We can see the (v2.2.6.RELEASE) version number and the port of Tomcat:

But at this time we go to visit 127.0.0.1:8080, there will be a 404 reminder:


We can create a new HelloController under the project:

@RestController
public class HelloController {
    @GetMapping("/hello")

    public String hello(){
        return "Hello World!";
    }
}

At this point, when we visit, we can see the following:

Of course, more often we finish writing an application, which needs to be put on the server to run. At this time, we need to package the application. To package the application, we need to configure it in pom.xml:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Of course, the SpringBoot created using idea is properly arranged for us. We only need to enter the following command in the terminal to package the entire project:

mvn package

Then we execute in the terminal:

java -jar target/demo-0.0.1-SNAPSHOT.jar

You can run the packaged project as follows:

Custom Banner

When the Spring Boot program starts, we will see the Spring Boot logo:

But usually, companies will replace it with their own company logo, so how to customize their own company logo?

First, we need to convert the file to a font in TXT text format, such as the setting at http://www.network-science.de/ascii/, for example, we set a SpringDemo font:

Then create a new banner.txt file in the project's resource directory, copy and paste the generated text into it:

Then when we re-run the program, we will find that the default Logo has been replaced:

If you want to close it is also very simple, just need to set in the main function:

SpringApplicationBuilder builder = new SpringApplicationBuilder(DemoApplication.class);
builder.bannerMode(Banner.Mode.OFF).run(args);

Web container configuration

In SpringBoot, we can configure the web container in application.properties as follows:

server.address=127.0.0.1 # 配置地址
server.port=8888 # 配置端口
server.tomcat.basedir=/opt/tmp # 配置目录
server.tomcat.uri-encoding=utf-8 #配置编码
server.tomcat.max-threads=300 #配置最大线程数

In idea, the configuration items are intelligently prompted, which is very convenient:

We can also configure the certificate in this file:

server.ssl.key-store= #配置秘钥文件名称
server.ssl.key-alias= #配置秘钥别名
server.ssl.key-password= # 配置证书密码

Application.properties file loading order

The application.properties configuration file in SpringBoot can appear in the following 4 locations:

  • In the config folder under the project root directory

  • Under the root directory of the project

  • under the config folder under classpath

  • under classpath

Developers can also customize the name of this file, just add spring.config.name = xxx at runtime:

jar -jar xxx.jar --spring.config.name=xxx

You can also know the path where the configuration file is located:

jar -jar xxx.jar --spring.config.location=classpath:/

The configuration files of SpringBoot will eventually be loaded into the Environment. We can use @Value annotation and EnvironmentAware interface to talk about data injection into properties. For example, the contents of application.properties are as follows:

book.name=西游记
book.author=六承恩
book.price=66
book.type="古典文学","四大名著"

The contents of the Book class are as follows:

@Component
@ConfigurationProperties(prefix = "book")
public class Book {
    private String name;
    private String author;
    private Float price;
    private List<String> type;

    //getter 省略
    //seteer 省略
    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                ", type=" + type +
                '}';
    }
}

The prefix property in the ConfigurationProperties annotation describes the controller class corresponding to the prefix of the configuration file to be loaded as follows:

@RestController
public class BookController {
    @Autowired
    Book book;
    @GetMapping("/book")
    public String book(){
        return book.toString();
    }
}

After our visit, we can see the following:

In addition, YAML configuration is also supported. We delete or comment the content in application.properties, and then create a new application.yml file in resource. The content is as follows. The result of re-running the program is the same as above.

book:
  name: 西游记
  author: 六承恩
  price: 66
  type:
    -  古典文学
    - 四大名著

Although the file in YAML format is convenient, it cannot be loaded using the @PropertySource annotation.

Profile

In the actual development process, developers need to frequently switch between production and test environments, and some of the configuration needs to be changed, such as the configuration of the database. In this regard, SpringBoot provides @Profile annotation, we can configure two configuration files to represent the production and test environment, and create new application-dev.properties and application-prod.properties in the resource.

Then configure in the main function:

SpringApplicationBuilder builder = new SpringApplicationBuilder(DemoApplication.class);
    builder.application().setAdditionalProfiles("prod");
    builder.run(args);

Or add it when the project starts--spring.profiles.active=prod .

【END】

More exciting recommendations

☞The platform resists 700 million daily visits, and the R & D quality control process is fully disclosed

☞Dry dry goods! How to improve the performance of deep learning training several times?

☞ "Tear the LeetCode problem by hand and pick up pants with various algorithm routines"

☞The idea of ​​intelligent transportation caused by the traffic jam of Beijing Fourth Ring Road

from Ngin to Pandownload, programmers how to avoid prison for programming?

☞From Web1.0 to Web3.0: detailed analysis of the development and future direction of the Internet in these years

Every "watching" you order, I take it seriously

Published 1975 original articles · 40 thousand likes + · 18.32 million views

Guess you like

Origin blog.csdn.net/csdnnews/article/details/105631432