Springboot加载maven父子工程配置文件的方法

本文探讨了在Spring中如何使用@PropertySource、ResourceUtils和ClassPathResource加载配置文件,特别是处理父子工程同名配置文件时的加载优先级。通过ResourcePatternResolver展示了如何按特定模式加载多个配置文件,包括限制在主模块和加载所有模块的配置。

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

1、@PropertySource

父子工程同名配置文件,优先加载当前主模块的配置文件,主模块的配置文件没有加载子模块的配置文件 (默认resource下的配置文件)

@PropertySource(value={"classpath:skill-common.properties"}) 

2、ResourceUtils

 org.springframework.util.ResourceUtils

父子工程同名配置文件,优先加载当前主模块的配置文件,主模块的配置文件没有加载子模块的配置文件(默认resource下的配置文件)

URL url = null;
Properties pro = new Properties();
try {
    url = ResourceUtils.getURL("classpath:skill-common.properties");
    pro.load(url.openStream());
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

3、ClassPathResource 

org.springframework.core.io.ClassPathResource

父子工程同名配置文件,优先加载当前主模块的配置文件,主模块的配置文件没有加载子模块的配置文件(默认resource下的配置文件)

ClassPathResource resource = new ClassPathResource("skill-common.properties");
String path = resource.getPath();
Properties pro = new Properties();
try {
	pro.load(resource.getInputStream());
} catch (IOException e) {
	e.printStackTrace();
}

4、ResourcePatternResolver 资源匹配解析器

(默认resource下的配置文件)

1、只加载主模块的前缀skill-的配置文件

ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("skill-*.properties");
Properties pro = new Properties();
for (Resource resource : resources) {
    String path = resource.getURL().getPath();
    System.err.println(path);
    pro.load(resource.getInputStream());
}

2、配置文件路径加classpath*:    //加载父子模块所有前缀skill-的配置文件

ResourcePatternResolver resolverAll = new PathMatchingResourcePatternResolver();
Resource[] resourcesAll = resolverAll.getResources("classpath*:skill-*.properties");
Properties prop = new Properties();
for (Resource resource : resourcesAll) {
    String path = resource.getURL().getPath();
    System.err.println(path);
    prop.load(resource.getInputStream());
}

 

 

 

 

 

 

 

 

 

 

 


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值