@PropertySource 配置读取文件位置配置

使用场景:当我们打包发布文件是需要将配置文件拿出来配置,这个时候就需要配置读取文件的位置

配置如下:

@Data
@Configuration
@ConfigurationProperties()
@PropertySource(value = {"classpath:/test.properties","file:./config/test.properties","file:./test.properties"},ignoreResourceNotFound = true)
public class TestConfig {

    private String testFilePath;

}

classpath:/test.properties 读取jar包内的配置文件test.properties
file:./config/test.properties 读取jar包所处文件夹同级目录的config下配置文件test.properties
file:./test.properties 读取jar包所处文件夹同级配置文件test.properties
ignoreResourceNotFound指定是否忽略找不到的资源文件,默认是false,这意味着如果指定的资源文件不存在,会抛出异常;但在这里设置为true,表示即使找不到指定的资源文件也不会抛出异常,Spring会继续启动。

读取文件优先级根据配置路径从后向前读取配置

示例:

  • TestConfig 配置
@Data
@Configuration
@ConfigurationProperties()
@PropertySource(value = {"classpath:/test.properties","file:./config/test.properties","file:./test.properties"},ignoreResourceNotFound = true)
public class TestConfig {

    private String testFilePath;

}
  • 启动类输出TestConfig 读取文件地址
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class TestApplication implements ApplicationListener<WebServerInitializedEvent> {

    public static final Logger LOGGER = LoggerFactory.getLogger(TestApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    @Autowired
    private TestConfig testConfig;

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        LOGGER.info("TestConfig 读取文件地址:"+ testConfig.getTestFilePath());
    }

}

不同位置test.properties内容

config文件夹下test.properties内容
testFilePath=config

jar包同级目录test.properties内容
testFilePath=root

jar包内test.properties内容
testFilePath=jar

文件配置 jar包同级目录和config目录都存在test.properties
在这里插入图片描述
程序启动输出地址:root
在这里插入图片描述
文件配置 config目录下test.properties
在这里插入图片描述
程序启动输出地址:config
在这里插入图片描述
不进行外部文件配置
在这里插入图片描述
程序启动输出地址:jar
在这里插入图片描述

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值