Spring Boot (01) - Hello World
2019-08-26
Coding
Spring Boot
Spring
Java
👋 ‍️‍️阅读
❤️ 喜欢
💬 评论

Spring Boot (01) - Hello World

尽管网上已经有许许多多的Spring Boot教程,但是其侧重点总是在如何搭建和配置WEB服务而非Spring Boot本身。 本教程将着重于Spring Boot本身,一方面介绍核心特性的用法,一方面结合源码一步步揭开Spring Boot的"魔法"。

入门须知

  • Java 8 熟练
  • Maven 熟练
  • Java Annotation 理解
  • AOP(CGLIB) 了解

环境

  • Java 8+
  • Maven 3+
  • Spring Boot 2.x

Spring Boot是什么

  • Spring Boot是一个快速开发部署框架(容器), 帮助Java(Spring)开发者摆脱繁琐的配置
  • Spring Boot不是Web Server,构建Web服务只是其诸多子项目之一
  • Spring Boot核心特性
    • 依赖注入
    • 面向切面
    • 自动配置(无XML配置文件)
    • 独立部署

Spring Boot提供的是一个快速开发框架,在其之上集成了许多组件集合可以开发各类应用,其中最常见的就是Web服务。本教程将主要针对Spring Boot本身和Spring Boot Web进行讲解。

  • 本文将不区分Spring和Spring Boot
  • 本文使用SpringBoot:2.1.7
  • 不建议使用https://start.spring.io/初始化项目,在学习阶段你应该从零开始搭建项目

Hello World

首先我们创建一个标准的maven工程,然后添加以下内容

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.7.RELEASE</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>

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

dependencyManagement引入spring-boot-starter-parent来管理依赖,这样所有Spring Boot相关依赖不再需要声明版本。

有关maven import scope的详细内容请参看[官方文档](https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html)

引入依赖项spring-boot-starterstarter项目是一类帮助快速构建应用的工具项目,其包括了构建该类应用的必备和首选依赖,例如spring-boot-starter-web就包括了spring-boot, web, json, validator, tomcat等依赖。

接下来写我们Java文件

Application.java

package xdean.share.spring.helloworld;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public String world() {
        return "world";
    }

    @Autowired
    public void hello(String who) {
        System.out.println("Hello " + who);
    }
}

典型的Spring Boot应用入口都形如该类。

  • 标有@SpringBootApplication (在接下来的章节中将详细讲解)
  • main中通过SpringApplication.run来启动应用

方法world定义了一个Bean, 方法hello注入了这个Bean并输出到控制台。

运行代码你将看到

  .   ____          _            __ _ _
 /\\ / ___&#39;_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | &#39;_ | &#39;_| | &#39;_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  &#39;  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.7.RELEASE)

2019-08-28 17:26:44.092  INFO 22300 --- [           main] xdean.share.spring.helloworld.Application     : Starting Application on LT413286 with PID 22300 
2019-08-28 17:26:44.097  INFO 22300 --- [           main] xdean.share.spring.helloworld.Application     : No active profile set, falling back to default profiles: default
Hello world //HL
2019-08-28 17:26:44.736  INFO 22300 --- [           main] xdean.share.spring.helloworld.Application     : Started Application in 0.982 seconds (JVM running for 2.436)

可以看到我们成功地输出了Hello World

该例演示了如何创建一个Spring Boot应用以及简单的依赖注入。

Hello Web

同样的我们创建一个maven工程,不同的是我们的依赖项从spring-boot-starter变成了spring-boot-starter-web。顾名思义,这个starter将帮助我们构建一个web应用。

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.7.RELEASE</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>

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

同样的我们定义一个Application作为应用的入口

package xdean.share.spring.helloweb;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

接着我们创建一个新的类WebHandler

package xdean.share.spring.helloweb;

@RestController
public class WebHandler {
    @GetMapping("/hello")
    public String helloWorld() {
        return "Hello World";
    }
}
  • 这个类被标记为了@RestController
  • 他有一个方法helloWorld被标记为了@GetMapping("/hello")
后文将详解他们的工作原理

看上去这个WebHandlerApplication之间没有任何联系

让我们运行Application看看

  .   ____          _            __ _ _
 /\\ / ___&#39;_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | &#39;_ | &#39;_| | &#39;_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  &#39;  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.7.RELEASE)

2019-08-28 17:39:34.214  INFO 20384 --- [           main] xdean.share.spring.helloweb.Application  : Starting Application on LT413286 with PID 20384 
2019-08-28 17:39:34.217  INFO 20384 --- [           main] xdean.share.spring.helloweb.Application  : No active profile set, falling back to default profiles: default
2019-08-28 17:39:35.100  INFO 20384 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-08-28 17:39:35.118  INFO 20384 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-08-28 17:39:35.118  INFO 20384 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.22]
2019-08-28 17:39:35.186  INFO 20384 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-08-28 17:39:35.186  INFO 20384 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 917 ms
2019-08-28 17:39:35.335  INFO 20384 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService &#39;applicationTaskExecutor&#39;
2019-08-28 17:39:35.459  INFO 20384 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path &#39;&#39;
2019-08-28 17:39:35.461  INFO 20384 --- [           main] xdean.share.spring.helloweb.Application  : Started Application in 1.684 seconds (JVM running for 3.146)

Spring Boot告诉我Tomcat已经启动,我们不需要单独配置Web Server便可以启动服务。让我们来试试看我们的API是否上线成功

$ curl localhost:8080/hello
Hello World

可以看到我们的Web服务已经可用。

该例演示了如何快速搭建Web服务,同时也体现了Spring Boot的自动配置。

小结

通过上面两个例子,想必你已经感受到了Spring Boot的简洁强大。

接下来的章节我们将详细讲解Spring Boot的各个特性并结合源码详解。


Copyright © 2020-2024 Dean Xu. All Rights reserved.