Reputation: 21
I have a use case where I need to refer to configuration files from various nested JARs within a Spring Boot fat JAR
public void searchConfFiles() throws Exception {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// Search for all .conf files in the nested JARs
Resource[] resources = resolver.getResources("classpath:/BOOT-INF/lib/**/*.conf");
System.out.println("resoucre length"+resources.length);
for (Resource resource : resources) {
if (resource.exists()) {
try (InputStream inputStream = resource.getInputStream()) {
String content = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
System.out.println("Found .conf file: " + resource.getURI());
System.out.println(content);
}
}
}
}
It is displaying a resource length of 0, even though the .conf files are included.
The approach should work when running the application using the jar command, gradlew bootRun, or the maven command.
Does Spring provide a solution for this ?
Any other alternatives ?
Upvotes: 0
Views: 118
Reputation: 1
I see you got the solution already, may be this would be a beautified version and below can be added under a configuration class and read over auto wired bean:
@Value("classpath*:/*.conf")
private Resource[] configResources;
Arrays.stream(configResources).forEach(resource -> {
try {
System.out.println("URI: "+resource.getURI() + "Content: "+resource.getContentAsString(StandardCharsets.UTF_8));
//Here configurations can be initialized as java objects and can be read over getters.
} catch (IOException e) {
throw new RuntimeException(e);
//If needed application can be terminated if these are mandatory configurations.
}
});
Upvotes: 0
Reputation: 20543
Those jars are in classpath so you can use resolver.getResources("classpath:/*.conf")
.
Correction: according to @DeepuVarma solution is
resolver.getResources("classpath*:/*.conf")
Upvotes: 2