Use Maven to build SpringBoot projects

foreword

There are many online introductions on how to create Springboot projects, most of which are based on IDE development tools and managed by Maven. If the current development environment is not sufficient, we can directly use Maven commands to create and manage SpringBoot projects. For those who are accustomed to using commands to create projects It is more convenient and better understand SpringBoot's project structure.

1. Create a Maven project

1.1 Create a simple Java project using Maven

Take VSCode as an example, Ctrl + ` shortcut key to open the terminal
insert image description here
Assuming the name of the project is example
, enter the following Maven command in the console to generate

mvn archetype:generate
 "-DgroupId=com.project"
 "-DartifactId=example" 
 "-DarchetypeArtifactId=maven-archetype-quickstart"
 "-DinteractiveMode=false"
  1. -DgroupId=com.project: group id.
  2. -DartifactId=example: project name, maven will create a new directory named this name in the current directory according to this name to build the project.
  3. -DarchetypeArtifactId: Project archetype, which archetype is used to create the initial structure of the project, here, we first use maven-archetype-quickstart to create a simple Java application.
  4. -DinteractiveMode=false : Whether it has been carried out in interactive mode, if it is false, the project will be built with default settings.

After the creation is successful, as shown in the figure, the console shows
insert image description here

1.2 Project Structure Introduction

insert image description here

Note: The above build is just a simple Java project. If we are building a Web project, we also need to adjust the directory structure to facilitate our subsequent development. We need to make the following adjustments.

  1. We don't need these two files App.java and AppTest.java, they can be deleted directly.
  2. Add a resources directory under the main directory to store resource files.
  3. Create the example package under the example/src/main/java/com/project package, and create the exampleApplication.java class under the /example package as the startup item of the entire project.

After adjustment, the directory structure is shown in the following figure:
insert image description here

1.3 Add project dependencies

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.project</groupId>
  <artifactId>example</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>example</name>
  <url>http://maven.apache.org</url>
  <description>用户权限管理系统</description>
  <!-- 设置父模块,这样就可以继承父模块中的配置信息 -->
  <parent>
    <!-- Springboot依赖 -->
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.1.RELEASE</version>
    <relativePath/>
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <!-- 添加 web 依赖 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  </dependencies>
  
  <build>
    <plugins>
      <!-- Spirng Boot Maven 插件 -->
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

1.4 Add startup class

Add the main method to the startup class and set it as the startup class.

package com.project.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@ServletComponentScan
@SpringBootApplication
public class exampleApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(exampleApplication.class,args);
        System.out.println("你好,这里是example项目");
    }
}

1.5 Compile and package the project

Enter the following command in the terminal to download dependencies

mvn clean install

After execution, the project structure is as follows:
insert image description here

After executing the above statement (or after creating the project), there is an additional target directory under the project root directory. The target is used to store the jar package, war package and compiled class files after the project is built. All the contents in the target directory are generated during the project construction process of Maven.

1.6 Add controller content

The project is built successfully, let's write a Controller interface to verify whether the project is successfully created

  1. Create a system package (with any name) under the example/src/main/java/com/project/example package to store business-related code.
  2. Add the controller package under the system package to store the class of the front-end interface controller.
  3. Add the FirstController.java class under the controller package as the test class for project startup.
package com.project.system.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController//Controller 里面的方法都以 json 格式输出
public class FirstController {
    
    
    @GetMapping("/first")
    public String first(){
    
    
        return "你好";
    }
}

2. Start the project

The following will introduce two common ways to start a project in the console.

  1. Start the project with Maven.
  2. Run the jar package to start the project.

Here we use the Maven command to start the project

2.1 Use Maven to start the project

mvn package 编译打包
mvn spring-boot:run 启动项目

After the startup is complete, if the console appears as shown in the figure below, the startup is successful:
insert image description here

3. Detailed Explanation of SpringBoot Configuration File

3.1 Configuration file instructions

In the Spring Boot project, configuration files in the following two file formats are supported.

application.properties
application.yml

Let's take a look at the difference between the properties configuration file and the yml configuration file.

  • application.properties is a regular key=value format configuration file, for example:
# 默认加载配置项
spring.profiles.active=prod
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=root

The properties file has a disadvantage. When there are many parameters to be configured, you will find that its hierarchy is not so clear and it is not easy to read. And many names at the same level are repeated.

  • The basic writing method of the yml file is: key: (space) value . It is worth noting that the key and the value are connected by a colon and a space. Both are indispensable, otherwise the configuration item cannot be read. The case is as follows.
spring:
  profiles:
    active: prod
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test
    username: root
    password: root

Note: The relationship between the upper and lower levels is represented by spaces. There is no requirement for the number of spaces, as long as the left-aligned column of data is at the same level. For the sake of aesthetics, it is recommended to use tab indentation or uniform 4 spaces to distinguish the upper and lower levels.

Both the properties file and the yml file are used as configuration files, and their purpose is not different. Compared with the properties configuration file, the yml configuration file has a stronger sense of hierarchy when written. The format officially recommended by Spring is the .yml format, so most of the configuration files of Spring Boot's Web projects currently use yml files. In this article, we will also use the yml file as the configuration file of the project.

3.2 Configure ports and paths

Create the application.yml file in the /src/main/resources directory, and write the following configuration content, we can modify the root path of the project.

server:
  # 配置端口
  # port: 8080
  servlet:
    # 设置项目路径
    context-path: /example

After adding, we repackage and run the project.

mvn package 编译打包
mvn spring-boot:run 启动项目

Open the browser and enter localhost:8080/upms/hello to visit, as shown in the figure below:
insert image description here

3.3 Custom Configuration Properties

In addition to the configuration provided by the system, we can also add the following custom configuration in application.yml.

server:
  # 配置端口
  port: 8080
  servlet:
    # 设置项目路径
    context-path: /example

# 自定义配置
example:
  name: example
  version: 0.0.1
  description: example项目

If we want to use configuration items, we only need to add the annotation @Value("${property name}") before the properties of the class, and we can add the following content in controller/FirstController.java:

package com.project.example.system.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController // Controller 里面的方法都以 json 格式输出
public class FirstController {
    
    
    @Value("${example.name}")
    private String appName;

    @Value("${example.version}")
    private String appVersion;

    @Value("${example.description}")
    private String appDescription;

    @GetMapping("/Msg")
    public String Msg() {
    
    
        return "名称:" + appName + "," +
               "版本:" + appVersion + " ," +
               "描述" + appDescription;
    }

    @GetMapping("/first")
    public String first() {
    
    
        return "你好";
    }
}

After adding, we repackage and run the project.

mvn package 编译打包
mvn spring-boot:run 启动项目

Open the browser and enter localhost:8080/upms/Msg to access, as shown in the figure below:

insert image description here

3.4 Multi-environment configuration

In the process of developing a project, a set of programs may need to be released in different environments, and its database configuration, port configuration or other configurations are different. It is very easy to configure if you modify the corresponding environment configuration every time as needed Wrong, causing unnecessary trouble.
Usually in this case, we can configure different configuration files for different environments to solve. In the Spring Boot project, the following two formats are supported by default.

  • application-{name}.properties
  • application-{name}.yml

where {name} corresponds to the environment ID. We can also create different configuration files in the Spring Boot project, and the file name is in the format of application-{name}.yml.

  • application-dev.yml development environment
  • application-test.yml test environment
  • application-prod.yml production environment

We create the configuration file shown in the figure below under the src/main/java/resources directory.
insert image description here
Add the following content to the application-dev.yml configuration file.

# 自定义配置
example:
  name: example
  version: 0.0.2
  description: example项目(开发环境)

Add the following information to the application-prod.yml configuration file.

# 自定义配置
example:
  name: example
  version: 0.0.3
  description: example项目(生产环境)

Add the following information to the application-test.yml configuration file.

# 自定义配置
example:
  name: example
  version: 0.0.4
  description: example项目(测试环境)

Add the following information to the application-test.yml configuration file.

# 自定义配置
example:
  name: example
  version: 0.0.4
  description: example项目(测试环境)

Then add spring.profiles.active to the configuration file application.yml to set the current environment, where test means that the application-test.yml configuration file is enabled by default.
insert image description here

You can also modify the test to dev or prod and test to see the effect, we will not demonstrate it here.

4. Personalized Banner Configuration

We noticed that when the Spring Boot project starts, the console will print the built-in Banner, as shown in the figure below: What insert image description here
if we also want to customize one, here is a website for customizing Banner
English ASCII artistic words, Spring Boot custom startup Banner Online Generation Tool
Text and pictures can be displayed, how to show it is up to you.
Just create a banner.txt file in the /resources directory, add the following location:
insert image description here
and add the following content in the banner.txt file.

                                   _ __     _            
   ___    __ __   __ _    _ __    | '_ \   | |     ___   
  / -_)   \ \ /  / _` |  | '  \   | .__/   | |    / -_)  
  \___|   /_\_\  \__,_|  |_|_|_|  |_|__   _|_|_   \___|  
_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""| 
"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-' 

After adding, Spring Boot will load this file when it starts, and recompile and run to see the effect.

mvn package 编译打包
mvn spring-boot:run 启动项目

insert image description here
It's not very useful, but it looks cool, hahaha

Finish

In this article, I introduced how to use Spring Boot to build a Java Web project, install, package and run the entire project through the Maven tool, after the project is built, set custom configuration items, and use the configuration information in the project for Different environments customize different configuration items. And provide a simple request to verify the running effect of the project, and finally customize a Banner for the project.

The above is my personal learning and use experience. If there is something wrong, please point it out and welcome everyone to discuss.

Guess you like

Origin blog.csdn.net/m0_59420288/article/details/128177819