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

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());
}
 
经验分享 程序员 微信小程序 职场和发展