java andexpect_Spring Boot: 编写一个 Hello World 应用(Java & Maven)

v2-c3c12315d18e119d76bd371585ca8b71_1440w.jpg?source=172ae18b

本文介绍如何使用 Spring Boot CLI 快速创建一个 Web 应用,编写一个非常简单的 “Hello World”,使用 Maven 构建并运行起来。

1. 介绍

内容简介: 一个简单的 Spring Boot Web 应用示例
语言框架: Java、Spring Boot、Spring MVC
难度级别: L1
阅读时间: 10 分钟

2. 工具准备

  • Java SDK : 8.0+
  • Spring Boot CLI : 2.1.2
  • Maven : 3.6.0
  • STS : 4.0
  • Curl / HTTPPie

3. 实现步骤

3.1. 创建项目

首先,通过 Spring CLI 创建一个空白工程: Hello World 应用。

$ spring init --name hello-world --artifactId spring-boot-hello-world 
--groupId org.springdev.guides --package-name org.springdev.guides.helloworld 
--language java --build maven 
--dependencies web,devtools --extract

3.2. 打开项目

打开 STS,点击菜单 File Import,选择导入向导 Maven 下的 Existing Maven Projects,在下一步中选择刚刚创建的工程目录,确定后导入到 STS 中。

3.3. 项目结构

此时创建的新工程目录结构如下:

├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── org
    │   │       └── springdev
    │   │           └── guides
    │   │               └── helloworld
    │   │                   └── HelloWorldApplication.java
    │   └── resources
    │       ├── application.properties
    │       ├── static
    │       └── templates
    └── test
        └── java
            └── org
                └── springdev
                    └── guides
                        └── helloworld
                            └── HelloWorldApplicationTests.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 http://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.1.2.RELEASE</version>                     
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>org.springdev.guides</groupId>
  <artifactId>spring-boot-hello-world</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>hello-world</name>
  <description>Demo project for Spring Boot</description>

  <properties>
    <java.version>1.8</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-devtools</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

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

</project>
  • 代码说明如下:
    Spring Boot 版本使用 2.1.2.RELEASE
  • 项目的起步依赖:webdevtoolstest
  • Spring Boot 插件,用于打包和运行应用。

在 Package Explorer 中打开应用主程序文件: HelloWorldApplication.java,可以看到这个文件代码非常简单。

package org.springdev.guides.helloworld;

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

@SpringBootApplication
public class HelloWorldApplication {

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

3.4. 编写代码

3.4.1. 编写 Controller

接下来我们开始编写 Controller。在 src/main/java/org/springdev/guides/helloworld/ 目录中新增一个 HelloController.java,内容如下:

package org.springdev.guides.helloworld;

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

@RestController  
public class HelloController {

    @GetMapping("/hello")  
    public String hello() {
        return "Hello, World!";  
    }

}

代码说明如下:

  • Spring MVC 提供了@RestController注解,这是一个 REST 接口类;
  • 设置 Get 请求,请求地址为/hello
  • 响应成功,并返回内容为:Hello, World!

3.5. 单元测试

3.5.1. 编写测试用例

package org.springdev.guides.helloworld;

...

@RunWith(SpringRunner.class)
@SpringBootTest  
@AutoConfigureMockMvc
public class HelloControllerTests {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void hello() throws Exception {
        this.mockMvc.perform(get("/hello"))  
            .andDo(print())
            .andExpect(status().isOk())  
            .andExpect(content().string("Hello, World!"));  
    }

}

代码说明如下:

  • Spring Boot 提供了@SpringBootTest注解,该注解简化了 Spring Boot 应用的测试,提供了对应 spring-test 中@ContextConfiguration的功能,用于创建ApplicationContext
  • 自动配置MockMvc实例,用于模拟执行请求/hello
  • 验证响应状态码为200,表示成功;
  • 验证返回内容为:Hello, World!

3.5.2. 执行单元测试

mvn test

运行结果

2019-01-14 19:40:11.860  INFO 71447 --- [           main] o.s.g.helloworld.HelloControllerTests    : Started HelloControllerTests in 1.902 seconds (JVM running for 2.661)

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /hello
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {}

Handler:
             Type = org.springdev.guides.helloworld.HelloController
           Method = public java.lang.String org.springdev.guides.helloworld.HelloController.hello()

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"text/plain;charset=UTF-8", Content-Length:"13"]
     Content type = text/plain;charset=UTF-8
             Body = Hello, World!
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.653 s - in org.springdev.guides.helloworld.HelloControllerTests
2019-01-14 19:40:12.159  INFO 71447 --- [       Thread-4] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  5.106 s
[INFO] Finished at: 2019-01-14T19:40:12+08:00
[INFO] ------------------------------------------------------------------------

4. 构建运行

选中工程,然后打开菜单 Run Run as Spring Boot App,应用就开始启动了,可以在控制台看到启动应用的日志。

或者,在控制台下执行命令:

mvn spring-boot:run

运行结果如下:

  .   ____          _            __ _ _
 / / ___'_ __ _ _(_)_ __  __ _    
( ( )___ | '_ | '_| | '_ / _` |    
 /  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |___, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.2.RELEASE)

2019-01-14 19:47:13.422  INFO 71332 --- [  restartedMain] o.s.g.helloworld.HelloWorldApplication   : Starting HelloWorldApplication on Michaels-MBP.lan with PID 71332 (/Users/rain/Development/springdev/guides/spring/spring-boot-hello-world/complete/target/classes started by rain in /Users/rain/Development/springdev/guides/spring/spring-boot-hello-world/complete)
2019-01-14 19:47:13.426  INFO 71332 --- [  restartedMain] o.s.g.helloworld.HelloWorldApplication   : No active profile set, falling back to default profiles: default
2019-01-14 19:47:13.481  INFO 71332 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2019-01-14 19:47:13.482  INFO 71332 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2019-01-14 19:47:14.790  INFO 71332 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-01-14 19:47:14.825  INFO 71332 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-01-14 19:47:14.826  INFO 71332 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.14]
2019-01-14 19:47:14.837  INFO 71332 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/rain/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
2019-01-14 19:47:14.911  INFO 71332 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-01-14 19:47:14.911  INFO 71332 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1429 ms
2019-01-14 19:47:15.113  INFO 71332 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-01-14 19:47:15.289  INFO 71332 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2019-01-14 19:47:15.359  INFO 71332 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-01-14 19:47:15.364  INFO 71332 --- [  restartedMain] o.s.g.helloworld.HelloWorldApplication   : Started HelloWorldApplication in 2.346 seconds (JVM running for 2.746)

5. 测试验证

打开浏览器,访问地址: http://localhost:8080/hello 会看到下图所示的界面:

v2-77835a111d8c1c8f109cb94c5ef8ffa9_b.jpg

或者,通过 curl 来验证:

$ curl -v http://localhost:8080/hello
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /hello HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 200
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 13
< Date: Mon, 14 Jan 2019 11:47:50 GMT
<
* Connection #0 to host localhost left intact
Hello, World!

或者,通过 HTTPie 验证:

$ http :8080/hello
HTTP/1.1 200
Content-Length: 13
Content-Type: text/plain;charset=UTF-8
Date: Mon, 14 Jan 2019 11:47:24 GMT

Hello, World!

6. 小结

恭喜,你已经学会使用 Spring Boot CLI 创建一个 Spring Boot Web 简单应用,并且使用 Maven 构建运行起来。

7. 源码下载

原文: Spring Guides

源码: springdev-guides/spring-boot-hello-world

更多内容,请关注 “Spring技术社区”,后续会有更多其他流行框架和语言开发的 </Hello World> 学习教程,感谢阅读!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值