Using springboot 3.1.5 and I need to keep .properties files external to the jar so I am starting my app with
java -jar --spring.config.location=file:path/to/directory/
this finds application.properties without an issue. But if I add another.properties file to the same directory, spring does not load that file. How can I tell Spring to load all the .properties files in that directory without having to list them all manually
Regards
You can import them programmatically via main
method and set them into spring.config.import
, this is a demonstration.
@SpringBootApplication
public class ServiceParentApplication {
public static void main(String[] args) {
Arrays.stream(args)
.filter(arg -> arg.startsWith("--spring.config.location=file:")) // Incase you read folder application.properties via args
.map(arg -> arg.replace("--spring.config.location=file:", ""))
.findFirst()
.ifPresent(folder -> {
try (Stream<Path> paths = Files.walk(Paths.get(folder))) {
var importFiles = paths
.filter(Files::isRegularFile)
.map(file -> file.toString())
.filter(fileName -> fileName.endsWith("properties") || fileName.endsWith("properties") && !fileName.endsWith("application.properties"))
.map(fileName -> "optional:file:" + fileName)
.collect(Collectors.joining(";"));
System.setProperty("spring.config.import", importFiles);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
SpringApplication.run(ServiceParentApplication.class, args);
}
Here is the document for Optional Locations . Also, if you don't use .properties
file as the additional import, you can prefer configuration tree to import each file for each variable.
Thank you @seenukarthi for the suggestion that I refer to build this.