SpringBoot--加载配置文件

配置文件的位置

1.默认位置

SpringBoot的默认配置文件名称为application.properties,SpringBoot将从以下列表加载application.properties文件,并将它们添加到Spring Environment中:

  1. 部署时,jar包所在目录的/config子目录
  2. jar包所在目录
  3. classpath目录下的/config子目录
  4. classpath目录

这个列表是按照优先级排序的,如果存在多个重名的application.properties的话,列表中位置高的将覆盖位置低的。

2.自定义位置

如果不喜欢application.properties这个文件名或者需要自定义配置文件的位置,可以在启动SpringBoot应用的时候,传入一个spring.config.location参数,指定配置文件的位置和名称。例:
java -jar xxxx.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
上述例子加载了两个配置文件,分别是位于classpath目录下的default.properties和override.properties文件。

加载配置文件的属性

在配置文件application.properties中配置属性:
test.name = wahaha
test.age = 27
test.tel = 18800118888

1.@Component和@Value("${“xxx”}")

在类中获取配置文件的属性:

@Component
public class Configurations {
    
    @Value("${test.name}")
    private String name;

    @Value("${test.age}")
    private String age;

    @Value("${test.tel}")
    private Long tel;

    // getter and setter
}

在类的域属性上通过@Value("${xxxx}")指定关联属性,SpringApplication会自动加载。

2.@ConfigurationsProperties(prefix=“test”)

在上述方法中,手动书写@Value还是比较繁重的工作,好在SpringBoot提供了更加简洁的方式–@ConfigurationsProperties(prefix=“test”)。
prefix指定了配置文件中属性的前缀是test,并按照属性名进行自动匹配。例如:

@Component
@ConfigurationProperties(prefix = "test")
public class Configuration {

    private String name;

    private String age;

    private Long tel;

    // setter getter
}

另外,@ConfigurationsProperties(prefix=“test”,locations=“xxx.properties”)可以指定配置文件的位置和名称

根据运行环境加载不同的配置

1.Profiles

Profiles提供了一种隔离应用程序配置的方式,并让这些配置只能在特定的环境下生效。在配置文件中,用spring.profiles.active属性来指定特定环境的配置文件。在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:

  • application-dev.properties:开发环境
  • application-test.properties:测试环境
  • application-prod.properties:生产环境
    至于哪个具体的配置文件会被加载,需要在application.properties文件中通过spring.profiles.active属性来设置,其值对应{profile}值。例如:
    application.properties配置:spring.profiles.active = dev即指定application-dev.properties会被加载。

2.通过启动参数指定运行环境

通过命令启动:

java -jar xxxxx.jar --spring.profiles.active=prod

3.加载多个配置文件

例如:

spring.profiles.active = dev,database

等于告诉Spring Boot加载application-dev.properties和application-database.properties文件,从而实现多个配置文件的加载。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值