大家好,我是星星,一个曾经被Spring XML配置折磨到怀疑人生的Java开发者。以前写一个“Hello World”都要配置一堆beans.xml,感觉自己不是在开发,是在给Spring写情书。今天,我要带大家用Spring Boot从零搭建一个完整的入门项目——不写XML、不打WAR包、开箱即用,还自带热部署和各种黑魔法。

这个项目覆盖了Spring Boot几乎所有核心入门知识点:自动配置、YAML配置、多环境Profile、@Value和@ConfigurationProperties、随机值、校验、全局异常、热部署……我保证讲得详细又幽默,就像在跟你聊天,而不是上课。

准备好了吗?让我们开始这场“Spring Boot初恋”之旅!

1. 项目准备:像搭积木一样简单

首先,用IDEA的Spring Initializer快速创建项目(或者手动建Maven项目)。我们用的是Spring Boot 2.7.18(经典稳定版),JDK 17也行。

pom.xml 重点(我加了注释)

XML

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

<dependencies>
    <!-- Web起步依赖:内嵌Tomcat + Spring MVC,一键搞定 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- 校验依赖:让你优雅地告诉前端“你填错了!” -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
    
    <!-- 热部署神器:改代码不用重启,幸福感+10086 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
</dependencies>

幽默小贴士:以前写Spring项目,依赖版本冲突能让你怀疑人生。现在有spring-boot-starter-parent,它就像一个严厉但靠谱的家长,帮你管好所有孩子的版本。

2. 主启动类:整个应用的“心脏”

Java

package com.qcby.springbootdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication  // 三合一注解:配置 + 自动配置 + 组件扫描
@ImportResource("classpath:beans.xml") // 兼容老项目,加载传统XML配置(虽然我们几乎不用)
public class PracticeApplication {
    public static void main(String[] args) {
        SpringApplication.run(PracticeApplication.class, args);
    }
}

这个类就是你的应用入口。@SpringBootApplication是Spring Boot的灵魂,它偷偷干了三件事:

  • @Configuration:标记这是一个配置类
  • @EnableAutoConfiguration:开启自动配置(后面详细讲)
  • @ComponentScan:自动扫描组件

幽默比喻:以前你要手动配置Tomcat、DispatcherServlet……现在?Spring Boot说:“宝贝别哭,我都帮你配好了。”

3. Hello World + 配置注入:从简单到花里胡哨

Controller(最热闹的地方)

Java

@RestController
@PropertySource("classpath:custom.properties") // 加载自定义配置文件
public class PersonController {

    @Value("${server.port}") // 直接注入配置值
    private String port;
    
    @Value("${my.random}") // 随机值,每次启动都不一样
    private String random;
    
    @Value("${custom.message}") // 来自custom.properties
    private String customMessage;

    @Autowired
    private PersonProperties personProperties; // 用@ConfigurationProperties批量注入

    @GetMapping("/hello")
    public String hello() {
        return "Hello World!<br>" +
               "当前端口: " + port + "<br>" +
               "随机数: " + random + "<br>" +
               "自定义消息: " + customMessage + "<br>" +
               "批量配置: " + personProperties;
    }
}

访问 http://localhost:8080/bootdemo/hello 就能看到各种配置值。

配置注入两种方式对比

  1. @Value:适合零星取值,像点外卖单点菜。
  2. @ConfigurationProperties:批量绑定,适合一整套配置,像点套餐。

Java

@Component
@ConfigurationProperties(prefix = "person") // 前缀person的所有配置都绑进来
public class PersonProperties {
    private String name = "default-user";
    private int age = 20;
    private String description;
    
    // getter/setter + toString
}

4. YAML配置:比properties好看100倍

application.yml(推荐用这个,层级清晰):

YAML

server:
  port: 8080
  servlet:
    context-path: /bootdemo

my:
  random: ${random.int(10000)}  # 随机值,超好玩

person:
  name: default-user
  age: 20
  description: "用户 ${person.name} 年龄 ${person.age},随机值 ${my.random}"

# 多环境Profile演示(用---分隔)
---
spring:
  config:
    activate:
      on-profile: dev
server:
  port: 8081
person:
  name: dev-user

---
spring:
  config:
    activate:
      on-profile: prod
server:
  port: 8082
person:
  name: prod-user

启动加 --spring.profiles.active=dev 就能切换环境。占位符${}超级强大,还支持默认值${xxx:默认值}。

5. 数据校验 + 全局异常处理:不让垃圾数据进来

Java

public class Person {
    @NotBlank(message = "姓名不能为空")
    private String name;
    
    @Min(value = 0, message = "年龄不能为负")
    private Integer age;
    // getter/setter
}

Java

@RestController
@RequestMapping("/validate")
public class ValidateController {
    @PostMapping("/person")
    public Person validate(@Valid @RequestBody Person person) {
        return person; // 校验失败自动抛异常
    }
}

全局异常处理(优雅返回错误):

Java

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleValidationExceptions(
            MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach(error -> {
            String field = ((FieldError) error).getField();
            errors.put(field, error.getDefaultMessage());
        });
        return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
    }
}

幽默提醒:以前校验要自己写一堆if,现在Spring Boot说:“我来当恶人,你负责温柔返回错误就行。”

6. 热部署 + 自动配置报告

加了devtools依赖后,改代码Ctrl+F9就能热部署(IDEA需开启Build Project Automatically)。

在application.properties加:

properties

debug=true

启动时控制台会打印超长的自动配置报告,告诉你哪些配置生效了(Positive matches),哪些没生效(Negative matches)。这才是真正理解Spring Boot魔法的钥匙!

7. 小彩蛋:@ImportResource和自定义properties

我们加了个空的beans.xml和custom.properties,就是为了演示还能兼容老项目。Spring Boot虽然推全注解,但它很包容,不会嫌弃你的“前任”XML。

结语:Spring Boot,让开发变得性感

一天时间,我们从零搭建了一个功能完整的Spring Boot项目:Hello World、配置注入、多环境、校验、异常处理、热部署……最重要的是,几乎没写配置,全靠自动配置魔法。

Spring Boot就像一个贴心的恋爱对象:你想要什么,它就自动给你配好,还支持热更新(改bug不重启,幸福感爆棚)。

星星的忠告:别停留在Hello World,赶紧去试试数据库、Security、微服务……Spring Boot的世界,比你想象的更大更爽!

喜欢这篇幽默教程的同学,点个赞、收藏、转发(虽然这是聊天,但你可以心里给我点个赞)。明天继续Spring Boot第二天:整合MyBatis+Druid,敬请期待!

(完) —— 星星,2026年1月24日于东京(虽然我可能在被窝里写这篇)

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐