Spring Boot 读取配置文件的几种方式

本文介绍SpringBoot中配置文件的两种读取方式:通过环境变量和注解。包括基本配置、不同数据类型的读取、指定配置文件及使用数组或集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Boot 读取配置文件的方式可以分为
1. 注解
2. 获取 Spring Boot 的环境变量
来获取配置文件的信息,其中注解的方式又有集中表现形式。

第一步:创建 Spring Boot 工程( Maven 工程添加 Spring Boot 相应的依赖)。
这里写图片描述
这里写图片描述
这里写图片描述
现在我们只是测试 Spring Boot 的 配置文件的读取,不需要其他的依赖,所以什么都没选,直接下一步 – 下一步 – 完成,项目目录结构如下:
这里写图片描述
此时的 application.properties 的内容为空
这里写图片描述
POM 文件内容为:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.china.prop</groupId>
    <artifactId>springboot-properties</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot-properties</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</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 文件中的依赖是 IDEA 通过这种创建工程的方式给我们自动生成的。

第二步:在配置文件中添加一些测试信息。
这里写图片描述

string.port=1111
integer.port=1111

db.link.url=jdbc:mysql://localhost:3306/test
db.link.driver=com.mysql.jdbc.Driver
db.link.username=root
db.link.password=root

上面的配置变量仅仅是为了测试而添加的,不具有实际意义。string.port 与 integer.port 都是string 类型普通变量,这里只是做个名称区分而已。

一、 通过获取环境变量来获取配置参数

1.1. 主类

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

@SpringBootApplication
public class SpringbootPropertiesApplication {

    public static void main(String[] args) {
        // 获取 Spring Boot 上下文
        ConfigurableApplicationContext ctx = SpringApplication.run(SpringbootPropertiesApplication.class, args);
        // ctx.getEnvironment(); // 获取 边境变量
        System.out.println("===========================================");
        //获取字符串
        System.out.println("String: " + (ctx.getEnvironment().getProperty("string.port") + 1111) );

        //获取整数
        System.out.println("Interger:   " + (ctx.getEnvironment().getProperty("integer.port",Integer.class) + 1111 ));
        System.out.println(ctx.getEnvironment().getProperty("db.link.url"));
        System.out.println(ctx.getEnvironment().getProperty("db.link.driver"));
        System.out.println(ctx.getEnvironment().getProperty("db.link.username"));
        System.out.println(ctx.getEnvironment().getProperty("db.link.password"));
        System.out.println("===========================================");

    }
}

1.2. 运行主类

===========================================
String: 11111111
Interger:   2222
jdbc:mysql://localhost:3306/test
com.mysql.jdbc.Driver
root
root
===========================================

可以看到配置文件中相同格式的port变量,可以获取到不同的格式数据。

  1. 1 新建 bean,通过注入环境变量来获取配置信息。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class MyConf {

    @Autowired
    private Environment env;

    public void show(){
        System.out.println("===========================================");
        //获取字符串
        System.out.println("String: " +env.getProperty("string.port") + 1111);

        //获取整数
        System.out.println("Interger:   " + (env.getProperty("integer.port",Integer.class) + 1111 ));
        System.out.println(env.getProperty("db.link.url"));
        System.out.println(env.getProperty("db.link.driver"));
        System.out.println(env.getProperty("db.link.username"));
        System.out.println(env.getProperty("db.link.password"));
        System.out.println("===========================================");
    }
}

2.2 改造主类并运行

public static void main(String[] args) {

                ConfigurableApplicationContext ctx = SpringApplication.run(SpringbootPropApplication.class, args);

        MyConf myconf = (MyConf) ctx.getBean("myConf");
        myconf.show();

        ctx.close();
    }

结果:

===========================================
String: 11111111
Interger:   2222
jdbc:mysql://localhost:3306/test
com.mysql.jdbc.Driver
root
root
===========================================

二、通过注解获取配置文件信息

  1. 改造上面的 bean 配置类 MyConf:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyConf {

    @Value("${string.port}")     private int intPort;
    @Value("${string.port}")     private  String stringPort;
    @Value("${db.link.url}")     private String dbUrl;
    @Value("${db.link.driver}")  private String dbDriver;
    @Value("${db.link.username}")private String dbUsername;
    @Value("${db.link.password}")private String dbPassword;

    public void show(){
        System.out.println("===========================================");
        System.out.println("intPort :   " + (intPort + 1111));
        System.out.println("stringPort :   " + (stringPort + 1111));
        System.out.println("string :   " + dbUrl);
        System.out.println("string :   " + dbDriver);
        System.out.println("string :   " + dbUsername);
        System.out.println("string :   " + dbPassword);
        System.out.println("===========================================");
    }
}
  1. 运行主类可得:
===========================================
intPort :   2222
stringPort :   11111111
string :   jdbc:mysql://localhost:3306/test
string :   com.mysql.jdbc.Driver
string :   root
string :   root
===========================================
  1. 指定配置文件,@PropertySource可以声明多个,
    或者使用@PropertySources(@PropertySource(“xxx”),@PropertySource(“xxx”))。
    2.1 新建配置文件 my.prop
aaa.a=111
aaa.b=222
aaa.c=333

2.2 新建配置类

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:config/my.prop")
public class PropConf {

    @Value("${aaa.a}")
    private String a;
    @Value("${aaa.b}")
    private String b;
    @Value("${aaa.c}")
    private String c;

    public void show(){
        System.out.println("a --- > " + a);
        System.out.println("b --- > " + b);
        System.out.println("c --- > " + c);
    }
}

2.3. 在主类中添加相应调用代码

PropConf conf = (PropConf) ctx.getBean("propConf");
conf.show();

2.4. 结果:

a --- > 111
b --- > 222
c --- > 333

改造一

可以改造上面的PropConf 类:添加@ConfigurationProperties(prefix = “aaa”)
指定配置文件的前缀,生成giter 和 setter 方法来获取配置信息。


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:config/my.prop")
@ConfigurationProperties(prefix = "aaa")
public class PropConf {

    private String a;
    private String b;
    private String c;

    public String getA() {return a;}
    public void setA(String a) {this.a = a;}
    public String getB() {return b;}
    public void setB(String b) {this.b = b;}
    public String getC() {return c;}
    public void setC(String c) {this.c = c;}

    public void show(){
        System.out.println("a --- > " + a);
        System.out.println("b --- > " + b);
        System.out.println("c --- > " + c);
    }
}

运行主类可以获得同样的结果。

改造二

可以只声明 setter 方法:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:config/my.prop")
@ConfigurationProperties(prefix = "aaa")
public class PropConf {

    private String a;
    private String b;
    private String c;

    public void setA(String a) {  this.a = a;  }
    public void setB(String b) { this.b = b;  }
    public void setC(String c) {  this.c = c; }

    public void show(){
        System.out.println("a --- > " + a);
        System.out.println("b --- > " + b);
        System.out.println("c --- > " + c);
    }
}

运行主类也可以得到同样的结果:

a --- > 111
b --- > 222
c --- > 333

=======================================

笔记1

上面获取配置文件的位置都是在 classpath 根目录下面的,Spring Boot 默认的配置文件地址有两个:(application.properties 为默认的配置文件名称)
1. classpath: 即放在resources里面。
2. classpath:config里面。
这里写图片描述
3. file:/
4. file:/config/

笔记2

在系统系统时可以通过 –spring.config.name=xxx.properties 环境变量指定配置文件。
比如resources下有一个 dblink.properties,然后添加启动参数:
这里写图片描述

笔记3 应用启动可以指定配置文件地址

这里写图片描述

笔记4 Spring Boot 配置文件可以使用变量

这里写图片描述

笔记5 配置文件可以使用数组或者集合

  1. 在配置文件中添加集合信息
aaa.host[0]=127.0.0.1
aaa.host[1]=10.66.0.108
aaa.host[2]=10.66.0.111
aaa.host[3]=10.66.0.12
aaa.host[4]=10.66.0.134
  1. 在配置类中注入参数
    这里写图片描述
  2. 输出 host变量 可得:
[127.0.0.1, 10.66.0.108, 10.66.0.111, 10.66.0.12, 10.66.0.134]
Spring Boot框架中,读取配置文件(通常是`application.properties`或`application.yml`)中的属性值可以借助一些特定的注解来完成。以下是几种常用的方式及其对应的注解: ### 1. 使用 `@Value` 这是最直接的一种方式,用于将单个配置项注入到字段中。 ```java @Value("${property.key}") private String propertyKey; ``` 例如,在`application.properties`中有如下配置: ```properties app.name=MyApp app.version=1.0.0 ``` 那么可以在代码里通过下面的方式获取它们的值: ```java @Value("${app.name}") private String appName; @Value("${app.version}") private String appVersion; ``` --- ### 2. 使用 `@ConfigurationProperties` 当需要一次性绑定一组相关的属性时,推荐使用这种方式。它更适合管理复杂的、分组式的配置数据。 首先创建一个POJO类,并标注上`@ConfigurationProperties(prefix="prefix")`和`@Component`(让其被Spring容器扫描)。比如: ```java @Component @ConfigurationProperties(prefix = "app") public class AppConfig { private String name; private String version; // 需要有getter/setter方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } } ``` 此时无需再单独标记每个成员变量为`@Value`形式了。 注意点:为了保证安全性以及避免意外的数据覆盖情况发生,建议开启校验功能: ```yaml spring: config: activate: on-profile: dev # 指定激活环境(dev/test/prod等) ``` 同时还可以结合`@Validated`来进行参数验证操作。 --- ### 3. 其他补充说明 除了上述两种主流做法之外,还有一些场景化的特殊处理手段可供参考学习,如动态刷新配置(`@RefreshScope`)配合云原生架构下的服务发现机制;又或者是利用Environment接口手动查找键值对等等……
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值