Java Spring Boot入门:Hello World

Spring Boot把Spring框架的复杂配置做了大量简化,开箱即用、约定大于配置。从零开始创建一个Spring Boot项目,到跑通第一个REST接口,大概只需要10分钟。

创建项目

最简单的方式是用Spring Initializr:

  1. 打开 https://start.spring.io
  2. 选择:
    • Project: Maven
    • Language: Java
    • Spring Boot: 2.6.x(选最新稳定版)
    • Group: com.example
    • Artifact: demo
    • Packaging: Jar
    • Java: 11
  3. Dependencies添加:Spring Web
  4. 点Generate下载zip

解压后用IDEA或VS Code打开。

也可以用命令行(需要安装Spring Boot CLI):

spring init --dependencies=web --java-version=11 --type=maven-project demo

目录结构

demo/
├── pom.xml
└── src/
    ├── main/
    │   ├── java/com/example/demo/
    │   │   └── DemoApplication.java
    │   └── resources/
    │       ├── application.properties
    │       ├── static/
    │       └── templates/
    └── test/
        └── java/com/example/demo/
            └── DemoApplicationTests.java

核心文件:

  • DemoApplication.java:启动类
  • application.properties:配置文件
  • pom.xml:Maven依赖管理

启动类

package com.example.demo;

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

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

@SpringBootApplication是一个组合注解,等价于:

  • @Configuration:声明配置类
  • @EnableAutoConfiguration:开启自动配置
  • @ComponentScan:组件扫描

编写Controller

创建HelloController.java

package com.example.demo.controller;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class HelloController {

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

    @GetMapping("/hello/{name}")
    public String helloName(@PathVariable String name) {
        return "Hello, " + name + "!";
    }

    @GetMapping("/greet")
    public String greet(@RequestParam(defaultValue = "World") String name) {
        return "Greetings, " + name + "!";
    }
}

@RestController = @Controller + @ResponseBody,方法返回值直接作为HTTP响应体。

返回JSON

package com.example.demo.controller;

import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @GetMapping
    public Map<String, Object> listUsers() {
        List<Map<String, Object>> users = new ArrayList<>();
        users.add(Map.of("id", 1, "name", "Alice", "email", "alice@example.com"));
        users.add(Map.of("id", 2, "name", "Bob", "email", "bob@example.com"));

        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("data", users);
        return result;
    }

    @PostMapping
    public Map<String, Object> createUser(@RequestBody Map<String, String> body) {
        String name = body.get("name");
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "Created user: " + name);
        return result;
    }
}

Spring Boot内置了Jackson,对象会自动序列化为JSON。

application.properties

# 端口
server.port=8080

# 应用名称
spring.application.name=demo

# 日志级别
logging.level.root=INFO
logging.level.com.example.demo=DEBUG

# 数据库(如果用了spring-data-jpa)
# spring.datasource.url=jdbc:mysql://localhost:3306/demo
# spring.datasource.username=root
# spring.datasource.password=123456

也可以用application.yml格式:

server:
  port: 8080
spring:
  application:
    name: demo
logging:
  level:
    root: INFO
    com.example.demo: DEBUG

运行与测试

运行

# Maven
./mvnw spring-boot:run

# 或者先打包再运行
./mvnw package
java -jar target/demo-0.0.1-SNAPSHOT.jar

启动后可以看到:

Started DemoApplication in 2.3 seconds

测试

# 测试接口
curl http://localhost:8080/api/hello
# Hello, Spring Boot!

curl http://localhost:8080/api/hello/Jack
# Hello, Jack!

curl http://localhost:8080/api/users
# {"code":0,"data":[...]}

curl -X POST http://localhost:8080/api/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Charlie"}'
# {"code":0,"msg":"Created user: Charlie"}

单元测试

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@SpringBootTest
@AutoConfigureMockMvc
class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void testHello() throws Exception {
        mockMvc.perform(get("/api/hello"))
            .andExpect(status().isOk())
            .andExpect(content().string("Hello, Spring Boot!"));
    }

    @Test
    void testHelloName() throws Exception {
        mockMvc.perform(get("/api/hello/Jack"))
            .andExpect(status().isOk())
            .andExpect(content().string("Hello, Jack!"));
    }
}

小结

Spring Boot的核心就是自动配置和约定大于配置。创建项目用Initializr,写接口用@RestController,配置写在application.properties里,启动就是一个main方法。上手很快,后续可以根据需要加入Spring Data JPA、Spring Security、MyBatis等组件。