当前位置: 代码网 > it编程>编程语言>Java > SpringBoot读取application.yml作为配置的处理

SpringBoot读取application.yml作为配置的处理

2026年04月17日 Java 我要评论
spring boot 的一大优势是 “约定优于配置” + “配置外部化”。你不需要写 xml 或硬编码参数,而是把配置放在 application.y

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(适合少量配置)

# application.yml
app:
  name: myspringbootapp
  version: 1.0.0
@component
public class appconfig {
    @value("${app.name}")
    private string appname;
    @value("${app.version}")
    private string version;
}

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

步骤 1:在 application.yml 中配置

# application.yml
database:
  host: 192.168.1.100
  port: 3307
  username: admin
  password: secret123

步骤 2:定义配置类

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 中注入使用

@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

# application.yml
app:
  security:
    jwt:
      secret: mysecretkey
      expire-hours: 24
    cors:
      allowed-origins:
        - http://localhost:3000
        - https://myapp.com
@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

@component
@configurationproperties(prefix = "xxx")
public class xxxproperties { ... }

2. 在 @configuration 类上使用 @enableconfigurationproperties

@configuration
@enableconfigurationproperties({databaseconfig.class, appproperties.class})
public class appconfig { }

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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com