S1E1_say Hello World to Spring Boot

1.Introduce Spring Boot

Spring Boot helps you to create stand-alone, production-grade Spring-based applications that you can run. We take an opinionated view of the Spring platform and third-party libraries, so that you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.

You can use Spring Boot to create Java applications that can be started by using java -jar or more traditional war deployments. We also provide a command line tool that runs “spring scripts”.

Our primary goals are:

  • Provide a radically faster and widely accessible getting-started experience for all Spring development.
  • Be opinionated out of the box but get out of the way quickly as requirements start to diverge from the defaults.
  • Provide a range of non-functional features that are common to large classes of projects (such as embedded servers, security, metrics, health checks, and externalized configuration).
  • Absolutely no code generation and no requirement for XML configuration.

对于Spring Boot介绍可以直观了解这款技术产品定位,它就是为简化Spring应用程序开发而生的,提供可以直接独立运行的、生产级的应用开发基础,使用JDK原生的java -jar就可以运行起来。

Spring Boot要实现的目标也是有野心的:

  1. 为所有Spring开发者提供更快更全面的入门体验
  2. 开箱即用,快速解决需求变更带来的问题
  3. 提供大量非功能性特性,比如内嵌服务器、安全特性、审计功能、健康检查、外部化配置
  4. 绝对不生成代码,不要求xml配置

整个Spring Boot就建立在这样的基础之上,而Spring Boot又为其他Spring项目提供基础设施。下面就从最简单的Hello World看下Spring Boot是如何做到radically faster和out of the box的。

2.系统配置

使用Spring Boot的必要系统配置只有JDK,就像标准Java应用一样。

但官方还是建议通过Build Tool(Maven or Gradle)这种支持依赖管理的工具来构建应用。

Spring Framework,Servlet Container等都可以通过内嵌集成。当然,官方提供的Spring Boot CLI也是可以的。

技术类别依赖名称版本要求
JDKJDK17+
SpringSpring Framework6.0.2+
Build ToolMaven3.5+
Build ToolGradle7.5+
Servlet ContainerTomcat10.0
Servlet ContainerJetty11.0
Servlet ContainerUndertow2.2
GraalVM Native ImagesGraalVM Community22.3
GraalVM Native ImagesNative Build Tools0.9.18

3.开发Hello World

以Maven构建为例创建第一个Spring Boot应用程序,当然前面几步可以直接从spring initializr生成。

3.1 创建POM

<?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>

    <groupId>com.example</groupId>
    <artifactId>myproject</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.0</version>
    </parent>

    <!-- Additional lines to be added here... -->

</project>

3.2 添加Classpath依赖

Spring Boot提供了大量Starters在项目路径中,我们在parent标签中使用spring-boot-starter-parent做冒烟测试。

spring-boot-starter-parent是一个提供诸多Maven默认值的的starter,通过依赖管理可以让开发者省去很多依赖版本管理的烦恼,但本身没有提供任何依赖。

其他的Starters则根据使用场景按需引用。

我们开发一个web应用,则引入spring-boot-starter-web,添加到pom.xml中。

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

再次查看项目的maven dependency:tree,就多了Tomcat web server和Spring Boot等依赖。

3.3 代码编写

还以Maven为例,代码结构组织约定默认编译src/main/java下的源码。

在这个目录根下创建启动类MyApplication.java,添加web处理请求注解。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class MyApplication {

    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

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

}
3.3. @RestController和@RequestMapping

他们都是Spring MVC的注解。

@RestController是stereotype注解,标记这是一个web @Controller,用于帮助Spring识别这是处理web请求的类,并使用字符串响应返回结果。

@RequestMapping提供路由信息,由它告知Spring任何带有/路径的Http请求都将映射到home方法。

3.3.2 @SpringBootApplication

另一个作用在class级别的注解是@SpringBootApplication,是一个meta-annotation,由@SpringBootConfiguration,@EnableAutoConfiguration和@ComponentScan组合而成。

@EnableAutoConfiguration让Spring Boot决定如何配置Spring,这就取决于添加到classpath中的依赖。这里通过spring-boot-starter-web添加的Tomcat和Spring MVC,自动装配就假定开发者要做web应用开发,从而配置Spring。

3.3.3 main方法

这是一个标准方法,遵循应用程序入口点的Java惯例。

我们main方法通过调用run方法代理Spring Boot的SpringApplicaion类,SpringApplication通过启动自动装配的Tomcat服务器,引导我们的应用程序启动Spring。我们需要将MyApplication.class作为run方法的入参告知SpringApplication它是Spring的主组件。run方法的args数组参数也支持命令行参数传入。

3.4 运行示例

在项目根目录命令行下输入mvn spring-boot:run就可以运行起来。

$ mvn spring-boot:run

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v3.0.0)
....... . . .
....... . . . (log output here)
....... . . .
........ Started MyApplication in 2.222 seconds (process running for 6.514)

在浏览器或模拟器中访问localhost:8080将会看到熟悉的输出:

Hello World!

退出则ctrl-c

3.5 创建可执行jar

为了能够在服务器上不间断运行,我们还需要最后一步,就是创建可执行jar。

对Spring Boot而言,可执行jar是开发者代码以及运行所需的全部jar依赖的编译文件合集,也就是常说的fat jars。(Java本身并没有提供标准用于加载nested jars)

创建可执行jar,引入spring-boot-maven-plugin,添加到pom.xml中。

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

注意,使用spring-boot-starter-parent绑定了repackage目标,如果不使用parent POM的话需要自己声明。

运行mvn package,得到如下结果:

$ mvn package

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building myproject 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] .... ..
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject ---
[INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:3.0.0:repackage (default) @ myproject ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

在target目录下,会生成myproject-0.0.1-SNAPSHOT.jar,这就是可执行jar,使用java -jar得到运行示例一样的结果:

$ java -jar target/myproject-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v3.0.0)
....... . . .
....... . . . (log output here)
....... . . .
........ Started MyApplication in 2.536 seconds (process running for 2.864)

同样的,退出则ctrl-c

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值