c++ properties_Spring Boot指定外部application.properties配置文件启动(实践)

本文介绍了如何在SpringBoot项目中通过修改pom.xml过滤.properties文件,创建spring.factories并编写LocalSettingsEnvironmentPostProcessor来加载外部的application.properties。详细步骤包括在pom.xml中配置过滤规则,创建并编辑spring.factories,以及编写Java代码实现环境处理器,从而实现启动时指定外部配置文件。

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

1.修改pom.xml,过滤src/main/resources目录下.properties文件

e938d794607a403576446e1b0905026a.png

pom.xml

pom.xml代码:

 XXXXorg.springframework.boot                spring-boot-maven-plugin            src/main/resources**/*.properties

2.在resources目录下创建META_INF/spring.factories文件(注意META_INF文件夹也是要创建的)

99f450a433949a0268117f96ff497a4e.png

spring.factories

spring.factories内容:

org.springframework.boot.env.EnvironmentPostProcessor=com.config.LocalSettingsEnvironmentPostProcessor

3.新建LocalSettingsEnvironmentPostProcessor.java加载外部属性文件application.properties

6c9aa00a53b035fd9e5ad358633230a2.png

LocalSettingsEnvironmentPostProcessor

LocalSettingsEnvironmentPostProcessor.java代码如下:

package com.config;import org.springframework.boot.SpringApplication;import org.springframework.boot.env.EnvironmentPostProcessor;import org.springframework.core.env.ConfigurableEnvironment;import org.springframework.core.env.MutablePropertySources;import org.springframework.core.env.PropertiesPropertySource;import org.springframework.core.io.FileSystemResource;import org.springframework.core.io.support.PropertiesLoaderUtils;import java.io.File;import java.io.IOException;import java.util.Properties;/** * @author 光州程序猿 * @version 1.0 */public class LocalSettingsEnvironmentPostProcessor implements EnvironmentPostProcessor {    private static final String LOCATION = "C:甥敳獲Desktopapplication.properties";    @Override    public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {        File file = new File(LOCATION);        try {            MutablePropertySources propertySources = configurableEnvironment.getPropertySources();            Properties properties = loadProperties(file);            propertySources.addFirst(new PropertiesPropertySource("Config", properties));        } catch (Exception e) {            e.printStackTrace();        }    }    private Properties loadProperties(File f) {        FileSystemResource resource = new FileSystemResource(f);        try {            return PropertiesLoaderUtils.loadProperties(resource);        } catch (IOException ex) {            throw new IllegalStateException("Failed to load local settings from " + f.getAbsolutePath(), ex);        }    }}

启动SpringBoot项目,指定外部application.properties启动成功。

b264729781826f2f5322d0595227667a.png

启动结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值