Spring Boot 如何读取 application.yml 作为配置

Spring Boot 的一大优势是 "约定优于配置" + "配置外部化"。

你不需要写 XML 或硬编码参数,而是把配置放在 application.yml(或 application.properties) 中,Spring Boot 自动加载并注入到你的应用中。

✅ 支持格式:.properties(键值对) 和 .yml(YAML,层次清晰,推荐)

Spring Boot 会按以下顺序查找 application.yml(后出现的会覆盖前面的):

  • 当前项目根目录下的 /config 子目录
  • 当前项目根目录下
  • classpath 下的 /config 包
  • classpath 根路径(即 src/main/resources/)

最常用:src/main/resources/application.yml

基本用法:在代码中读取配置

1.使用 @Value(适合少量配置)

java 复制代码
# application.yml
app:
  name: MySpringBootApp
  version: 1.0.0
java 复制代码
@Component
public class AppConfig {
    @Value("${app.name}")
    private String appName;

    @Value("${app.version}")
    private String version;
}

2.使用 @ConfigurationProperties(推荐!适合结构化配置)

步骤 1:在 application.yml 中配置

java 复制代码
# application.yml
database:
  host: 192.168.1.100
  port: 3307
  username: admin
  password: secret123

步骤 2:定义配置类

java 复制代码
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "database") // 对应 yml 中 database 开头的配置
public class DatabaseConfig {
    private String host = "localhost";
    private int port = 3306;
    private String username;
    private String password;

    // 必须有 getter/setter(或用 Lombok @Data)
    public String getHost() { return host; }
    public void setHost(String host) { this.host = host; }
    public int getPort() { return port; }
    public void setPort(int port) { this.port = port; }
    // ... 其他 setter/getter
}

步骤 3:在其他 Bean 中注入使用

java 复制代码
@Service
public class UserService {
    private final DatabaseConfig dbConfig;

    public UserService(DatabaseConfig dbConfig) {
        this.dbConfig = dbConfig;
    }

    public void connect() {
        System.out.println("连接数据库: " + dbConfig.getHost() + ":" + dbConfig.getPort());
    }
}

支持复杂结构:嵌套对象、List、Map

java 复制代码
# application.yml
app:
  security:
    jwt:
      secret: mySecretKey
      expire-hours: 24
    cors:
      allowed-origins:
        - http://localhost:3000
        - https://myapp.com
java 复制代码
@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
    private Security security = new Security();

    public static class Security {
        private Jwt jwt = new Jwt();
        private Cors cors = new Cors();

        public static class Jwt {
            private String secret;
            private int expireHours;
            // getters/setters
        }

        public static class Cors {
            private List<String> allowedOrigins = new ArrayList<>();
            // getter/setter
        }
        // getters/setters
    }
    // getter for security
}

启用 @ConfigurationProperties 的两种方式

1. 在配置类上加 @Component

java 复制代码
@Component
@ConfigurationProperties(prefix = "xxx")
public class XxxProperties { ... }

2. 在 @Configuration 类上使用 @EnableConfigurationProperties

java 复制代码
@Configuration
@EnableConfigurationProperties({DatabaseConfig.class, AppProperties.class})
public class AppConfig { }

不要同时用两种方式,否则可能创建多个实例

相关推荐
蔬菜_6 小时前
前端转全栈-day6(构造函数与继承)
java
程序员雷欧6 小时前
Java 反射深度解析:从原理到源码的全面剖析
java·开发语言·python
登登登__6 小时前
春秋招笔试题总结
java·开发语言
Undoom6 小时前
用TextIn xParse搞定批量简历解析,WorkBuddy里一句话就能完成
后端
rannn_1116 小时前
【力扣hot100】链表专题|21、2、19、24、92、25
java·数据结构·算法·leetcode·链表·开发
Rabitebla7 小时前
C++11 新特性详解(一):列表初始化、initializer_list 与右值引用
java·开发语言·数据结构·c++·算法·leetcode·list
洋不写bug7 小时前
JavaComparable、Comparator、Cloneable接口解析,深拷贝浅拷贝详细解析
android·java·开发语言
坐吃山猪7 小时前
WebFlux_学习Subscriber总结
java·开发语言·学习·webflux
乐橙开放平台7 小时前
一周上线校园透明化:listDeviceDetailsByPage 台账 + getKitToken + ImouPlayer 多路墙
后端·物联网·安全·音视频·智能家居
白露与泡影7 小时前
Java面试题及答案整理(2026年金九银十最新版,持续更新)
java·开发语言