Spring Boot从零入门3_创建Hello World及项目剖析

Stella981
• 阅读 928

本文属于原创,转载注明出处,欢迎关注微信小程序小白AI博客 和微信公众号别打名名或者网站 https://xiaobaiai.net 或者我的CSDN http://blog.csdn.net/freeape

Spring Boot从零入门3_创建Hello World及项目剖析

  • 1 前言

  • 2 名词术语

  • 3 创建Hello World项目

  • 3.1 基于STS4创建项目

  • 3.2 使用Spring Initializr Website创建项目并导入

  • 3.3 基于Spring Boot CLI创建项目

  • 3.4 各创建项目方式比较

  • 4 Spring Boot应用是如何工作的?

  • 4.1 pom.xml

  • 4.2 Spring Boot 注解(annotations)与应用入口

  • 5 总结

  • 6 参考资料

1 前言

上一篇我们讲述了Spring boot的几个核心模块,知道了Spring boot是如何减少组件依赖和简化繁杂的配置的,以及讲述了Spring boot减少组件依赖和简化繁杂配置的内部原理,最后完成了Spring boot的开发环境搭建。这一篇我们将讲述如何创建Spring boot Hello World级别的项目,创建一个简单的WEB应用,然后我们对这个项目层层剖析,让我们更深的了解Spring boot是如何工作的。

2 名词术语

名词术语

释义

CLI

命令行界面,command-line interface

Marven

Apache Maven是一个软件项目管理和综合工具,构建自动化系统(如Make,CMake)。基于项目对象模型(POM)的概念,Maven可以从一个中心资料片管理项目构建,报告和文件。Maven简化和标准化项目建设过程,处理编译,分配,文档,团队协作和其他任务的无缝连接。Maven增加可重用性并负责建立相关的任务;Marven拥有依赖管理功能,它通过简单的配置就可以自动从网络上下载项目所需的依赖

POM

项目对象模型(Project Object Model),它是Maven项目中的文件,使用XML表示,名称叫做pom.xml;该文件用于管理:源代码、配置文件、开发者的信息和角色、问题追踪系统、组织信息、项目授权、项目的url、项目的依赖关系等;Maven世界中,project可以什么都没有,甚至没有代码,但是必须包含pom.xml文件

Gradle

Gradle是一个完全开源的构建自动化系统,使用特定编程语言Groovy来书写配置文件,不同于Marven使用XML。如Android开发IDE Android Studio默认就是使用Gradle来构建项目;Gradle与Maven相比更为灵活,简单。

JDK8

JDK8或者JDK1.8是由于自从JDK1.5/JDK5命名方式改变后遗留的新旧命令方式问题。所以JDK8或者JDK1.8也是同一个东西。

STS

Spring Tool Suite,Spring Tools 4是适用于你喜欢的编码环境的下一代Spring工具。无论是你喜欢Eclipse,Visual Studio Code还是Theia IDE,STS是从头开始大量重构的,为开发基于Spring的企业应用程序提供了世界一流的支持。

Thymeleaf

Thymeleaf是现代化服务器端的Java模板引擎,不同与JSP和FreeMarker,Thymeleaf的语法更加接近HTML,并且也有不错的扩展性。

注解

注解只有成员变量,没有方法。注解的成员变量在注解的定义中以“无形参的函数”形式来声明,如int id();引用时如@TestAnnotation(id=3) 。注解中属性可以有默认值,默认值需要用 default 关键值指定,如public int id() default -1;注解的提取需要借助于 Java 的反射技术,反射比较慢,所以注解使用时也需要谨慎计较时间成本。注解主要给编译器及工具类型的软件用的。

元注解

元注解是可以注解到注解上的注解,或者说元注解是一种基本注解,但是它能够应用到其它的注解上面。如果把注解理解为标签,元注解也是一张标签,但是它是一张特殊的标签,它的作用和目的就是给其他普通的标签进行解释说明的。元标签有 @Retention、@Documented、@Target、@Inherited、@Repeatable 5 种

3 创建Hello World项目

创建一个Spring boot应用,有下面几种方式可以选择:

  • 使用IDE工具,如我们使用的STS4

  • 使用 Spring boot CLI工具

  • 使用 Spring Initializr网站来创建

下面对这三种方式一一讲述如何创建一个Spring boot WEB项目。

💡 STS(Spring Tool Suite)可以开发其他很多类型的项目,这里仅以Spring boot项目作为创建示例。

3.1 基于STS4创建项目

3.1.1 项目创建

基于STS4创建Spring Web项目,这里选择Marven Project项目类型或者是Spring Starter Project项目类型。Spring Stater Project跟下一小节所讲的Spring Initializr Website创建项目基本一致,只不过一个是集成在STS中,一个是独立的Web网站,下一小节细讲,这里就不展开了。这里选择Marven Project类型,开始创建。

Spring Boot从零入门3_创建Hello World及项目剖析

创建Marven项目中,我们选择Create a Simple Project,可以选择默认工作目录或者其他存放项目的目录,Next后需要我们填写一些项目信息,包括:

  • groupId:在所有项目中唯一标识你的项目。组ID应该遵循Java的程序包名称规则。这意味以反向域名开头(当然这不是强迫的,只是历史遗留下来的),如:

  • org.apache.maven

  • org.apache.commons

  • org.apache.maven.plugins

  • org.apache.maven.reporting

  • artifactId:是没有版本的jar的名称。如果创建了它,那么可以选择任何名称,包括小写字母和不是很奇怪的符号。如果是第三方jar,则必须使用该jar的名称。

  • version:如果发布了版本,则可以选择带有数字和点(1.0、1.1、1.0.1,...)的任何典型版本。不要使用日期,因为它们通常与 SNAPSHOT(快照)构建相关联。如果它是第三方artifact,则无论使用什么版本,都必须使用其版本号。

Spring Boot从零入门3_创建Hello World及项目剖析

Spring Boot从零入门3_创建Hello World及项目剖析

点击完成后,就创建了一个最简单的Marven项目,仅仅只有一个pom.xml文件,里面也只有我们创建的项目信息,接下来我们需要实现WEB服务器,访问一个简单的页面,页面显示出Hello World!

Spring Boot从零入门3_创建Hello World及项目剖析

3.1.2 添加工程代码

添加Spring WEB依赖项到pom.xml中:

<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.xiaobaiai.examples</groupId> <artifactId>test_01_helloworld</artifactId> <version>0.0.1-SNAPSHOT</version>    <!-- 下面为添加的依赖内容,spring-boot-starter-web --> <parent>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-parent</artifactId>  <version>2.2.0.RELEASE</version>  <relativePath /> <!-- lookup parent from repository --> </parent> <properties>  <java.version>11</java.version> </properties> <dependencies>  <dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-web</artifactId>  </dependency> </dependencies></project>

第二步,在src/main/java目录下新建一个Java文件:

Spring Boot从零入门3_创建Hello World及项目剖析

填写PackageName,点击Finish,创建完成,然后编写该Java文件:

package com.xiaobaiai;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@SpringBootApplication@Controllerpublic class Test01HelloworldApplication { @RequestMapping("/")    @ResponseBody    public String index() {        return "Hello World!";    }    public static void main(String[] args) {        SpringApplication.run(Test01HelloworldApplication.class, args);    }}

💡 在STS中,包一键导入快捷键Ctrl + Shift + o

3.1.3 运行Hell World Web应用

上述修改两个文件就完成一个基本的Hello World!级别应用,然后就可以运行了:选中项目-->菜单栏Run-->Run (Spring boot App)或者直接到工具栏找到快捷按钮(绿色右箭头),点击。接下来就可以看到在STS中的console(控制台)中看到Web 服务启动的过程了,没有出现错误,Tomcat initialized with port(s): 8080 (http),打开浏览器,输入http://localhost:8080回车可看到输出`Hello World!`,Demo成功:

Spring Boot从零入门3_创建Hello World及项目剖析

3.2 使用Spring Initializr Website创建项目并导入

3.2.1 STS中的Spring Initializr

通过Spring Initializr我们可以通过点击页面,选择我们所需要的依赖项,最终生成项目配置文件和应用文件。一般IDE中也集成了Spring Initializr,如STS中新建一个Spring Starter Project就可以操作Spring Initializr,在下一小节中我们将通过网站中的Spring Initializr来实现创建一个Web项目:

Spring Boot从零入门3_创建Hello World及项目剖析

3.2.2 网站的中Spring Initializr

在浏览器中打开https://start.spring.io,输入项目相关信息,并选择`Spring Boot及构建工具等,在DependenciesWeb栏中选中Spring Web,最后点击绿色按钮Generate - Ctrl`按钮生成工程文件压缩包,放于你的工作目录中并解压,然后用STS导入该项目:

Spring Boot从零入门3_创建Hello World及项目剖析

导入成功后,可以看到自动生成了上一小节中我们创建的pom.xmlXXApplication.java文件以及测试文件XXApplicationTests.java,其中pom.xml具体内容如下:

<?xml version="1.0" encoding="UTF-8"?><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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-parent</artifactId>  <version>2.2.0.RELEASE</version>  <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>com.xiaobaiai</groupId> <artifactId>test_02_helloworld</artifactId> <version>0.0.1-SNAPSHOT</version> <name>test_02_helloworld</name> <description>Demo project for Spring Boot</description> <properties>  <java.version>11</java.version> </properties> <dependencies>  <dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-web</artifactId>  </dependency>  <dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-test</artifactId>   <scope>test</scope>   <exclusions>    <exclusion>     <groupId>org.junit.vintage</groupId>     <artifactId>junit-vintage-engine</artifactId>    </exclusion>   </exclusions>  </dependency> </dependencies> <build>  <plugins>   <plugin>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-maven-plugin</artifactId>   </plugin>  </plugins> </build></project>

同样地我们把下面代码复制到Test02HelloworldApplication.java中(注意我们的类名改了,不是Test01了):

package com.xiaobaiai;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@SpringBootApplication@Controllerpublic class Test02HelloworldApplication { @RequestMapping("/")    @ResponseBody    public String index() {        return "Hello World!";    } public static void main(String[] args) {  SpringApplication.run(Test02HelloworldApplication.class, args); }}

最后点击Run,到浏览器中输入http://localhost:8080回车可看到输出`Hello World!`。

3.3 基于Spring Boot CLI创建项目

上一篇中我们已经介绍过Sping Boot CLI(命令行界面)这个工具了,它可用于快速使用Spring进行原型设计。使我们可以运行Groovy脚本,接下来我们实际操作一下。

3.3.1 安装Spring Boot CLI工具

从Spring软件存储库下载Spring CLI发行版,选择你工作的平台版本,这里选择了spring-boot-cli-2.2.0.RELEASE-bin.zip Windows版本:

下载好后,解压,然后配置好环境变量,则就安装成功,验证是否安装并配置好:

# 查看spring cli版本$ spring --versionSpring CLI v2.2.0.RELEASE# 查看spring所有帮助$ spring --help# 查看spring run命令帮助$ spring help run# 查看spring init命令帮助$ spring help init# 查看所有支持的dependencies,支持的工程类型(Project types,默认工程类型为marven-project)$ spring init --list

Spring Boot从零入门3_创建Hello World及项目剖析

$ spring init --list  .   ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )  '  |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/:: Service capabilities ::  https://start.spring.ioSupported dependencies+--------------------------------------+--------------------------------------------------------------+-------------------------------+| Id                                   | Description                                                  | Required version              |+--------------------------------------+--------------------------------------------------------------+-------------------------------+......| activemq                             | Spring JMS support with Apache ActiveMQ 'Classic'.           |                               || web                                  | Build web, including RESTful, applications using Spring MVC. |                               ||                                      | Uses Apache Tomcat as the default embedded container.        |                               |......+--------------------------------------+--------------------------------------------------------------+-------------------------------+Project types (* denotes the default)+-----------------+------------------------------------------+-----------------------------+| Id              | Description                              | Tags                        |+-----------------+------------------------------------------+-----------------------------+| gradle-build    | Generate a Gradle build file.            | build:gradle,format:build   || gradle-project  | Generate a Gradle based project archive. | build:gradle,format:project || maven-build     | Generate a Maven pom.xml.                | build:maven,format:build    || maven-project * | Generate a Maven based project archive.  | build:maven,format:project  |+-----------------+------------------------------------------+-----------------------------+Parameters+-------------+------------------------------------------+------------------------------+| Id          | Description                              | Default value                |+-------------+------------------------------------------+------------------------------+| artifactId  | project coordinates (infer archive name) | demo                         || bootVersion | spring boot version                      | 2.2.0.RELEASE                || description | project description                      | Demo project for Spring Boot || groupId     | project coordinates                      | com.example                  || javaVersion | language level                           | 1.8                          || language    | programming language                     | java                         || name        | project name (infer application name)    | demo                         || packageName | root package                             | com.example.demo             || packaging   | project packaging                        | jar                          || type        | project type                             | maven-project                || version     | project version                          | 0.0.1-SNAPSHOT               |+-------------+------------------------------------------+------------------------------+

3.3.2 使用Spring Boot CLI工具创建Hell World应用

接下来,我们直接使用Spring Boot CLI工具创建上述我们的Hello World WEB应用。

# 创建项目name: test_03_helloworld# groupId: com.xiaobaiai# artifactId: test_03_helloworld# language: java/groovy/kotlin# boot-version: 2.2.0# 构建工具类型: marven-project/marven-build/gradle-project/gradle-build# 依赖项(dependencies):web# java-version: java(jdk)版本# --package-name: 包名# --packaging:打包方式jar/war# --extract: 不加这个参数则创建出来的项目就是已经压缩过的,跟用Spring Initializr Website创建出来的一样# 最后一个test_03_helloworld即指定目标生成目录$ mkdir test_03_helloworld$ cd test_03_helloworld$ spring init -n test_03_helloworld -g com.xiaobaiai -a test_03_helloworld -l java -b 2.2.0.RELEASE -t maven-project -d web --extract -j 11 --package-name com.xiaobaiai --extract test_03_helloworld

💡 spring run命令只是针对Groovy语言的。

创建完成后,其实跟上述两种方式创建出来的工程是一样的,然后同样地,我们去修改src/main/java/com/xiaobaiai/Test03HelloworldApplication.java这个文件,添加一样的内容,这里就不贴代码了(可以使用文本编辑器如Vim/VS Code/Notepad++/Atom/Subline2等等)。

.├── HELP.md├── list│   ├── HELP.md│   ├── mvnw│   ├── mvnw.cmd│   ├── pom.xml│   └── src│       ├── main│       └── test├── mvnw├── mvnw.cmd├── pom.xml└── src    ├── main    │   ├── java    │   └── resources    └── test        └── java

💡 用Spring Boot CLI工具创建出来生成的工程文件默认是在当前文件夹中,如果加了--extract参数,则所有文件都解压出来,因此需要预先建立一个工程目录再执行创建命令。当然也可以指定生成文件夹,则会创建项目的时候创建该文件夹并将项目文件都生成到该文件夹中。

💡 另外还可以使用SDKMAN管理各种二进制SDK的多个版本,包括Groovy和Spring Boot CLI,具体的可以去官方文档了解。

接下来就是如何编译了。spring cli针对不同类型语言的WEB应用编译方式是不一样的,如果我们创建了Groovy语言类型的项目,那么只需要用到spring run组合命令就可以了,但是这里选择了java语言类型,则需要结合mvn(marven的命令行工具)和java(jdk的命令行工具)了。首先确保这两个命令已经配置好了环境变量。

Spring Boot从零入门3_创建Hello World及项目剖析

然后到项目根目录执行:

# spring-boot:run为Spring Boot Maven Plugin插件所支持,还有如spring-boot:repackage/spring-boot:start/spring-boot:stop/spring-boot:build-info。$ mvn spring-boot:run

最后到浏览器中输入http://localhost:8080回车可看到输出`Hello World!`。

3.4 各创建项目方式比较

  • 使用CLI工具创建大项目还是优点麻烦的,只是运行Groovy还可以选择一下

  • 使用 SPring Initializr工具方便快速

4 Spring Boot应用是如何工作的?

上面是一个简单的WEB应用,一一讲述了几种创建方式,并在浏览器中输出了Hello World!,那么整个应用是怎么运作的呢?这一节我们详细地来剖析下。

4.1 pom.xml

4.1.1 spring-boot-starter-parent

pom.xml是整个项目的核心配置文件,Marven的POM文件之间具有集成性,下面这段代码就表示POM文件继承自groupIdorg.springframework.bootartifactIdspring-boot-starter-parentversion2.2.0.RELEASE的POM文件。

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

spring-boot-starter-parent项目是一个特殊的启动程序项目,为我们的应用程序提供默认配置,并提供完整的依赖关系树以快速构建我们的Spring Boot项目。它还为Maven插件提供了默认配置,例如maven-failsafe-pluginmaven-jar-pluginmaven-surefire-pluginmaven-war-plugin。我们可以找到spring-boot-starter-parent-2.2.0.RELEASE.pom具体查看,如Windows系统中,该文件在C:\Users\{your username}\.m2\repository\org\springframework\boot\spring-boot-starter-parent\2.2.0.RELEASE\路径下。Linux平台在用户目录~/.m2/repository/org/springframework\boot\spring-boot-starter-parent\2.2.0.RELEASE\路径下。打开该文件后,我们可以看到spring-boot-starter-parent-2.2.0.RELEASE.pom又依赖了spring-boot-dependencies项目,这个文件里面定义了大部分底层依赖软件的版本号以及我们上一节介绍的Spring boot核心模块,如spring-boot-actuator等。我们可以从这个链接获取spring-boot-starter-parent的最新版本https://search.maven.org/classic/#search%7Cga%7C1%7Ca%3A%22spring-boot-starter-parent%22。

Spring Boot从零入门3_创建Hello World及项目剖析

4.1.2 spring-boot-starter-web

再到我们的应用这一层,我们依赖了spring-boot-starter-webspring-boot-starter-test(可以做单元测试)两个依赖。我们可以通过STS可以看到两个依赖里又包含了哪些依赖,如spring-boot-starter-web里面依赖了tomcat(实际用的是spring boot内嵌的tomcat)、spring-webspring-webmvc等。有了这些依赖其实就构成了我们实现一个Web Server的基础。

Spring Boot从零入门3_创建Hello World及项目剖析

另外,添加了父级依赖模块(spring-boot-starter-parent)后,在应用中添加其他依赖,我们是不需要指定版本了,所以的依赖版本已经在父级依赖中得到了管理(当然,我们也可以独立指定版本)。如:

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

4.1.3 dependencyManagement标签自定义父级依赖以及其他属性自定义

我们可以定义自己的一套父级版本依赖吗?当然是可以的,我们只需要定义<dependencyManagement>标记里内容就可以了,类似spring-boot-dependencies的POM文件里所示一样:

<dependencyManagement>    <dependencies>      <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot</artifactId>        <version>2.2.0.RELEASE</version>      </dependency>      <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-test</artifactId>        <version>2.2.0.RELEASE</version>      </dependency>      <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-test-autoconfigure</artifactId>        <version>2.2.0.RELEASE</version>      </dependency>      <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-actuator</artifactId>        <version>2.2.0.RELEASE</version>      </dependency>      <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-actuator-autoconfigure</artifactId>        <version>2.2.0.RELEASE</version>                ......            </dependencies></dependencyManagement>

为了自定义父级依赖中其他属性(配置),我们可以在相应位置重新去声明配置相关值,spring-boot-starter-parent通过其父级spring-boot-dependencies依赖使用属性来配置所有依赖项版本,Java版本和Maven插件版本等。因此,我们只需更改相应的属性即可自定义控制这些配置。比如我们想更改tomcat的版本,只需要在spring-boot-dependencies的POM文件中对应位置修改如下代码:

<properties>    ......    <tomcat.version>9.0.27</tomcat.version>    ......</properties>

4.1.4 自定义父级依赖

对于添加指定的父级依赖,而不是spring-boot-starter-parent,我们可以完全自定义配置我们所有的依赖,那么我们就需要配置类似spring-boot-starter-parent所有相关的内容,包括版本以及相关属性配置等。

4.1.5 Spring Boot Marven插件

pom.xml中还有这么一段代码:

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

上面的配置就是Spring Boot Maven插件,Spring Boot Maven插件提供了许多方便的功能:

  • 把项目打包成一个可执行的超级 JAR(uber-JAR),包括把应用程序的所有依赖打入JAR文件内,并为JAR添加一个描述文件,其中的内容能让你用 java -jar来运行应用程序。

  • 搜索 public static void main()方法来标记为可运行类。

4.2 Spring Boot 注解(annotations)与应用入口

4.2.1 注解(annotations)

在我们实现的简单Hello World Web项目中,我们使用了几个注解,如代码中所示的SpringBootApplicationController

@SpringBootApplication@Controllerpublic class Test02HelloworldApplication { @RequestMapping("/")    @ResponseBody    public String index() {        return "Hello World!";    } public static void main(String[] args) {  SpringApplication.run(Test02HelloworldApplication.class, args); }}

我们可以直接看到SpringBootApplication类中是什么内容,具体做了啥?它的定义如下:

@Target(ElementType.TYPE) // 元注解,指定了注解运用的地方,注解就被限定了运用的场景,此处限定为可以给一个类型进行注解,比如类、接口、枚举@Retention(RetentionPolicy.RUNTIME)  // 元注解, 注解可以保留到程序运行的时候,它会被加载进入到 JVM 中,所以在程序运行时可以获取到它们@Documented // 元注解,将注解中的元素包含到 Javadoc 中去@Inherited // 元注解,超类被 @Inherited 注解过的注解进行注解的话,那么如果它的子类没有被任何注解应用的话,那么这个子类就继承了超类的注解。@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),  @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })@ConfigurationPropertiesScanpublic @interface SpringBootApplication {    ......}

里面又有三个重要的注解:

「1) @SpringBootConfiguration」

该注解向类添加@Configuration注解,该注解将类标记为应用程序上下文的Bean定义的源。

「2) @EnableAutoConfiguration」

这告诉Spring Boot通过基于类路径设置,其他bean和各种属性设置添加bean,从而基于pom.xml中添加的依赖关系自动配置重要的bean定义。

「3) @ComponentScan」

该注解告诉Spring boot扫描基础包,查找其他的bean/组件,并对其进行配置。

「4) @Controller」 : 该注解指定了当前类Test02HelloworldApplication充当MVC中控制器作用,调度程序扫描带此类注解的类以查找映射的方法,并检测@RequestMapping注解。

「5)@RequestMapping」 : 你可以使用@RequestMapping注解将URL(例如/appointments)映射到整个类或特定的处理方法上。通常,类级别的注解将特定的请求路径(或路径模式)映射到表单控制器上,其他方法级别的注解使特定的HTTP请求方法(GET、POST等)的主映射范围变窄,或一个HTTP请求参数条件。下面是一个Controller + RequestMapping的示例:

@Controller@RequestMapping("/appointments")public class AppointmentsController {    private final AppointmentBook appointmentBook;    @Autowired    public AppointmentsController(AppointmentBook appointmentBook) {        this.appointmentBook = appointmentBook;    }    @RequestMapping(method = RequestMethod.GET)    public Map<String, Appointment> get() {        return appointmentBook.getAppointmentsForToday();    }    @RequestMapping(value="/{day}", method = RequestMethod.GET)    public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {        return appointmentBook.getAppointmentsForDay(day);    }    @RequestMapping(value="/new", method = RequestMethod.GET)    public AppointmentForm getNewForm() {        return new AppointmentForm();    }    @RequestMapping(method = RequestMethod.POST)    public String add(@Valid AppointmentForm appointment, BindingResult result) {        if (result.hasErrors()) {            return "appointments/new";        }        appointmentBook.addAppointment(appointment);        return "redirect:/appointments";    }}

在类级别上,如果没有@RequestMapping,想URL路径都是绝对的,而不是相对的,如我们Hello World WEB项目里代码所示。而上面的示例都是相对appointments路径。

4.2.2 应用入口及应用配置

在上一节中我们也提到了SpringApplication类的作用,只是没有实际项目来体会,这一节有了Hello World程序作为示例,我们再次来总结它的作用,进一步加深理解:

  • @SpringBootApplication是Sprnig Boot项目的核心注解,主要目的是开启自动配置,包括创建上下文内容,刷新应用上下文,并加载所有单例Bean

  • 在大多数情况下,可以直接从主方法中调用静态 run(Class, String [])方法来引导应用程序

  • 可以在应用运行之前创建和定制 SpringApplication实例,如:

    SpringApplication springApplication = new SpringApplication(SpringbootActionApplication.class);// 关闭应用启动时的Banner,如下://  .   ____          _            __ _ // /\ / _' __ _ ()_ __  __ _ \ \ \ //( ( )_ | '_ | '| | ' / ` | \ \ \ // \/  _)| |)| | | | | || (_| |  ) ) ) )//  '  || .|| ||| |_, | / / / /// =========||==============|_/=//_//// :: Spring Boot ::        (v2.2.0.RELEASE)springApplication.setBannerMode(Banner.Mode.OFF);springApplication.run(args);

在修改应用程序默认配置上,我们还可以通过src/main/resources/application.properties这个文件来配置。里面内容默认为空。常见配置有:

# 指定应用名(该名字在Spring Cloud应用中会被注册为服务名)spring.application.name=hello# 关闭Bannerspring.main.banner-mode=off# 修改WEB端口8080为8081server.port = 8081# 修改日志级别和中控台日志保存文件路径# 所有文件日志打印级别为WARNlogging.level.root=WARN# 指定包或具体类打印日志级别, 如logging.level.com.xiaobaiai=DEBUGlogging.level.{some.package.path}=DEBUG# 默认日志都会打印到控制台,你可以设定打印到文件,即直接指定路径和文件名logging.file=\path_to\logfile.log# 也可以只指定路径,默认为spring.loglogging.file.path=C:\\Work\\sts4\\test_02_helloworld\\logs# 自定义属性值,然后在应用程序中通过@Value注解来赋值,# @Value(value=”${com.xiaobaiai.name}”)# private String name;com.xiaobaiai.name="小白AI"

当然我们还可以在配置参数与配置参数之间进行引用,还可以使用指定配置参数文件,或者通过定义专用类来导入配置,这里就不展开了。

5 总结

这一节内容有点长,但是总的来说就是讲述了三种方式去创建一个Hello World WEB 项目,然后对这个WEB项目从pom.xml文件开始进行了分析,讲述了父级依赖,以及应用依赖和具体的版本依赖是如何实现的,最后对Spring Boot的应用入口和重要的几个注解也进行了讲解。完成这些,我们现在基本上对Spring Boot应用有了基本的了解了,接下来我们继续。

6 参考资料

文章难免疏漏,而公众号上每篇文章只能修改几个字,所以我会在我的小程序小白AI博客上也发一遍,任何的错误,我会在及时修改,欢迎随时交流。

关注我的公众号,获取最新学习分享:

Spring Boot从零入门3_创建Hello World及项目剖析

本文分享自微信公众号 - 别打名名(biedamingming)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Spring Boot从零入门1_详述
本文属于原创,转载注明出处,欢迎关注微信小程序小白AI博客和微信公众号别打名名或者网站https://xiaobaiai.net或者我的CSDNhttp://blog.csdn.net/freeape!(https://oscimg.oschina.net/oscnet/f8db20c4f3964337b76dc956a3a8
Wesley13 Wesley13
2年前
MQTT安全性设计详解
本文属于原创,转载注明出处,欢迎关注微信小程序小白AI博客微信公众号别打名名或者网站https://xiaobaiai.net或者我的CSDNhttp://blog.csdn.net/freeape!(https://oscimg.oschina.net/oscnet/ab92552a6bd64ed6a957d1854b677
Stella981 Stella981
2年前
Spring Boot从零入门6_Swagger2生成生产环境中REST API文档
本文属于原创,转载注明出处,欢迎关注微信小程序小白AI博客和微信公众号别打名名或者网站https://xiaobaiai.net或者我的CSDNhttp://blog.csdn.net/freeape!(https://oscimg.oschina.net/oscnet/cc3a3a51382349e5ab55c2a62f01
Stella981 Stella981
2年前
Spring Boot从零入门5_五脏俱全的RESTful Web Service构建
本文属于原创,转载注明出处,欢迎关注微信小程序小白AI博客和微信公众号别打名名或者网站https://xiaobaiai.net或者我的CSDNhttp://blog.csdn.net/freeape!(https://oscimg.oschina.net/oscnet/378afc2c41cd4b4ba99acadb9d83
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Spring Boot从零入门2_核心模块详述和开发环境搭建
本文属于原创,转载注明出处,欢迎关注微信小程序小白AI博客和微信公众号别打名名或者网站https://xiaobaiai.net或者我的CSDNhttp://blog.csdn.net/freeape!(https://oscimg.oschina.net/oscnet/824604023db348fd99425746632b
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这