分类课程智能体AI
文章
订阅
分类课程AI导师
文章
价格
课程进度
2 / 12
上一节Spring Boot 概览下一节创建你的第一个 Spring Boot REST API
自在学

© 2025 - 2026 株洲市自在学教育科技有限公司 版权所有

公网安备湘公网安备43020302000292号 | 湘ICP备2025148919号-1

关于我们隐私政策使用条款

© 2025 - 2026 株洲市自在学教育科技有限公司 版权所有

公网安备湘公网安备43020302000292号湘ICP备2025148919号-1

编程Spring Boot后端开发入门选择工具与开始

选择工具与开始

在开始构建Spring Boot应用之前,我们需要搭建一个完整的开发环境。这个过程不仅仅是安装几个软件那么简单,而是需要理解每个工具的作用、它们之间的协作关系,以及如何配置它们以获得最佳的开发体验。更重要的是,我们需要立即看到代码,通过实际的代码示例来理解Spring Boot项目的结构和工作方式。让我们从创建一个实际的项目开始,通过编写代码来学习。


使用Spring Initializr创建项目

Spring Initializr是Spring官方提供的项目初始化工具,它能够快速生成Spring Boot项目的骨架代码。让我们通过实际的例子来理解这个过程。假设我们要创建一个名为my-spring-boot-app的项目,使用Maven作为构建工具,Java 17作为JDK版本,Spring Boot 4.0.2作为框架版本,这也是当前Spring Boot的最新稳定版本。

通过访问start.spring.io,我们可以配置项目的基本信息。在Project字段选择Maven,Language选择Java,Spring Boot版本选择4.0.2,Project Metadata中Group填写com.example,Artifact填写my-spring-boot-app,Name填写My Spring Boot App,Package name填写com.example.myapp,Packaging选择Jar,Java版本选择17。在Dependencies部分,我们可以选择Spring Web起步依赖,这会自动包含构建RESTful Web应用所需的所有依赖。

点击Generate按钮后,会下载一个ZIP文件。解压这个文件,我们就能看到一个完整的Spring Boot项目结构。

使用Spring Initializr创建项目

让我们看看生成的关键文件。首先是pom.xml文件,这是Maven项目的核心配置文件:

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>4.0.2</version>
        <relativePath/>
    </parent>
    
    <groupId>com.example</groupId>
    <artifactId>my-spring-boot-app</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>My Spring Boot App</name>
    <description>My first Spring Boot application</description>
    
    <properties>
        <java.version>17</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>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

这个pom.xml文件定义了我们项目的基本信息。parent元素继承自spring-boot-starter-parent,这为我们提供了Spring Boot的默认配置和依赖管理。 dependencies部分包含了spring-boot-starter-web,这是构建Web应用的核心依赖,它自动包含了Spring MVC、Tomcat嵌入式服务器、Jackson JSON处理库等。 spring-boot-starter-test提供了测试框架的支持。build部分配置了spring-boot-maven-plugin,这个插件能够将应用打包成可执行的JAR文件。

展示Spring Initializr生成的项目结构,包括目录树和关键文件的内容,突出显示pom.xml、主应用类和配置文件


理解项目结构

现在让我们看看生成的项目结构。在src/main/java/com/example/myapp/my_spring_boot_app目录下,会有一个主应用类,通常命名为Application.java或MySpringBootAppApplication.java。让我们看看这个类的代码:

java
package com.example.myapp.my_spring_boot_app;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class MySpringBootAppApplication {
 
	public static void main(String[] args) {
		SpringApplication.run(MySpringBootAppApplication.class, args);
	}
 
}

这个类虽然简单,但它包含了Spring Boot应用启动所需的所有要素。@SpringBootApplication注解是一个组合注解,它等价于@Configuration、@EnableAutoConfiguration和@ComponentScan三个注解的组合。@Configuration表明这是一个配置类,@EnableAutoConfiguration启用Spring Boot的自动配置机制,@ComponentScan启用组件扫描,Spring会自动扫描当前包及其子包下的所有组件。

main方法是应用的入口点,SpringApplication.run()方法会启动Spring应用上下文,加载所有配置的Bean,启动嵌入式Web服务器。这个方法会阻塞,直到应用关闭。

现在让我们真正动手,在项目里加上第一个可访问的接口。打开IDE左侧的项目目录树,依次展开src、main、java、com.example.myapp、my_spring_boot_app这些层级,如果其中某一层不存在,就在上一级包上点击右键创建相应的包。确认已经能看到MySpringBootAppApplication所在的包之后,在这个包上点击右键,选择新建子包,输入名称controller并保存,这样磁盘上的实际路径就会是src/main/java/com/example/myapp/my_spring_boot_app/controller。接下来在这个controller包上再次点击右键,选择新建Java类,类名填写HelloController,IDE会自动在刚才这个目录下生成HelloController.java文件,完整路径就是src/main/java/com/example/myapp/my_spring_boot_app/controller/HelloController.java。打开这个新建的文件,把其中的内容替换为下面的代码:

java
package com.example.myapp.my_spring_boot_app.controller;
 
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, Spring Boot!";
    }
}

这个控制器类使用了@RestController注解,它结合了@Controller和@ResponseBody注解的功能。@Controller表明这是一个Spring MVC控制器,@ResponseBody表明方法的返回值应该直接写入HTTP响应体,而不是渲染到视图。@GetMapping("/hello")注解将HTTP GET请求映射到/hello路径,当访问这个路径时,会调用hello()方法并返回"Hello, Spring Boot!"字符串。

现在让我们看看src/main/resources目录下的配置文件。application.properties是Spring Boot的主配置文件:

properties
spring.application.name=my-spring-boot-app

这个配置文件设置了应用名称为my-spring-boot-app。

展示Spring Boot项目的完整目录结构,标注每个目录的作用,并显示关键文件的位置和内容示例


运行第一个应用

现在我们已经有了一个完整的Spring Boot项目,让我们运行它。在IDE中,我们可以直接运行主应用类的main方法。或者,我们可以使用Maven命令来运行:

bash
mvn spring-boot:run

这个命令会编译项目、下载依赖(如果需要)、启动应用。启动成功后,控制台会显示类似以下的输出:

shell
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v4.0.2)
 
2024-01-27 10:30:15.123  INFO 12345 --- [           main] c.e.myapp.MySpringBootAppApplication     : Starting MySpringBootAppApplication
2024-01-27 10:30:15.456  INFO 12345 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http)
2024-01-27 10:30:15.467  INFO 12345 enderedWebApplicationContext : Root WebApplicationContext: initialization completed in 1234 ms
2024-01-27 10:30:15.789  INFO 12345 --- [           main] c.e.myapp.MySpringBootAppApplication     : Started MySpringBootAppApplication in 2.456 seconds

从输出中可以看到,Spring Boot自动启动了Tomcat服务器,监听8080端口。现在我们可以通过浏览器访问http://localhost:8080/hello,应该能看到"Hello, Spring Boot!"的响应。

让我们创建一个更复杂的控制器,展示Spring Boot的更多特性:

java
package com.example.myapp.controller;
 
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import java.util.HashMap;
import java.util.Map;
 
@RestController
public class GreetingController {
 
    @GetMapping("/greeting")
    public Map<String, String> greeting(@RequestParam(defaultValue = "World") String name) {
        Map<String, String> response = new HashMap<>();
        response.put("message", "Hello, " + name + "!");
        response.put("timestamp", String.valueOf(System.currentTimeMillis()));
        return response;
    }
 
    @GetMapping("/user/{id}")
    public Map<String, Object> getUser(@PathVariable Long id) {
        Map<String, Object> user = new HashMap<>();
        user.put("id", id);
        user.put("name", "User " + id);
        user.put("email", "user" + id + "@example.com");
        return user;
    }
}

这个控制器展示了两个重要的Spring MVC特性。greeting方法使用了@RequestParam注解来接收查询参数,defaultValue属性设置了默认值"World"。getUser方法使用了@PathVariable注解来从URL路径中提取变量。这两个方法都返回Map对象,Spring Boot会自动将其序列化为JSON格式。

访问http://localhost:8080/greeting?name=Spring会返回

json
{
  "message":"Hello, Spring!",
  "timestamp":"1706347815123"
}

访问http://localhost:8080/user/123会返回

json
{
  "id":123,
  "name":"User 123",
  "email":"user123@example.com"
  }

Spring Boot的自动配置机制会根据类路径中的依赖自动配置相应的功能。当我们添加spring-boot-starter-web依赖时,Spring Boot会自动配置DispatcherServlet、消息转换器、错误处理等Web相关的组件。这种约定优于配置的方式大大简化了开发工作。

编写测试代码

Spring Boot提供了强大的测试支持。让我们为HelloController编写一个测试类:

java
package com.example.myapp.my_spring_boot_app.controller;
 
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
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.*;
 
@WebMvcTest(HelloController.class)
class HelloControllerTest {
 
    @Autowired
    private MockMvc mockMvc;
 
    @Test
    void testHello() throws Exception {
        mockMvc.perform(get("/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string("Hello, Spring Boot!"));
    }
}

这个测试类使用了@WebMvcTest注解,它会创建一个只包含Web层的测试上下文,不会加载完整的应用上下文,这使得测试运行更快。MockMvc是Spring Test提供的模拟MVC框架,我们可以用它来模拟HTTP请求并验证响应。testHello方法模拟了对/hello端点的GET请求,并验证响应状态码为200,响应内容为"Hello, Spring Boot!"。

我们还可以编写集成测试,测试完整的应用上下文:

java
package com.example.myapp.my_spring_boot_app;
 
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 MySpringBootAppApplicationTests {
 
    @Autowired
    private MockMvc mockMvc;
 
    @Test
    void contextLoads() {
        // 验证应用上下文能够成功加载
    }
 
    @Test
    void testGreetingEndpoint() throws Exception {
        mockMvc.perform(get("/greeting").param("name", "Test"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.message").value("Hello, Test!"));
    }
}

@SpringBootTest注解会加载完整的应用上下文,@AutoConfigureMockMvc会自动配置MockMvc。testGreetingEndpoint方法测试了greeting端点,使用jsonPath来验证JSON响应的内容。

展示Spring Boot应用的启动流程,从main方法调用到Tomcat服务器启动的完整过程,包括Bean的加载、自动配置的生效、Web服务器的初始化等步骤


配置开发工具

为了提高开发效率,我们可以添加Spring Boot DevTools依赖。在pom.xml中添加:

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>

DevTools提供了开发时的便利功能。当类路径中的文件发生变化时,DevTools会自动重启应用。它还禁用了模板缓存,这样修改模板文件后不需要重启就能看到变化。DevTools只在开发环境中生效,在生产环境中会被自动禁用。

我们还可以配置application.properties来优化开发体验:

properties
# Development configuration
spring.devtools.restart.enabled=true
spring.devtools.livereload.enabled=true
 
# Logging for development
logging.level.org.springframework.web=DEBUG
logging.level.com.example.myapp=DEBUG
 
# Show SQL queries (when using JPA)
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

这些配置启用了自动重启和LiveReload功能,设置了详细的日志级别以便调试,如果使用JPA还会显示SQL查询。

打包和运行

当我们完成开发后,可以使用Maven将应用打包成可执行的JAR文件:

bash
mvn clean package

这个命令会清理之前的构建产物,编译代码,运行测试,然后打包。打包完成后,在target目录下会生成my-spring-boot-app-0.0.1-SNAPSHOT.jar文件。这个JAR文件包含了应用的所有依赖,可以直接运行:

bash
java -jar target/my-spring-boot-app-0.0.1-SNAPSHOT.jar

这就是Spring Boot的“fat jar”特性,它将所有依赖打包到一个JAR文件中,使得部署变得非常简单。我们不需要配置外部服务器,不需要管理类路径,只需要一个JAR文件就能运行整个应用。


小结

通过这部分的学习,我们已经掌握了如何创建Spring Boot项目,理解了项目结构,编写了实际的代码,并成功运行了第一个应用。 在下一节中,我们将深入学习如何构建完整的REST API,包括请求处理、数据验证、异常处理等高级特性。

  • 使用Spring Initializr创建项目
  • 理解项目结构
  • 运行第一个应用
  • 编写测试代码
  • 配置开发工具
  • 打包和运行
  • 小结

目录

  • 使用Spring Initializr创建项目
  • 理解项目结构
  • 运行第一个应用
  • 编写测试代码
  • 配置开发工具
  • 打包和运行
  • 小结