То есть: я хочу сделать то же самое, что и Spring файл application.yml, но с другими файлами.
Файл не может быть файлом application.yml и будет храниться в пользовательской папке.
Пример:
Первый файл, my-custom-folder/my-custom-file.yaml
Код: Выделить всё
prop1: default-value-1
prop2: default-value-2
Код: Выделить всё
prop2: profile1-value-2
Код: Выделить всё
prop1: default-value-1
prop2: profile1-value-2
Код: Выделить всё
public final class ResourceLoaderUtil {
private static final String EMPTY_PROFILE = "";
record ProfiledResource(Resource resource, String profile) {}
private ResourceLoaderUtil() {
}
public static List getResources(String prefix, String extension, String[] activeProfiles) throws IOException {
PathMatchingResourcePatternResolver loader = new PathMatchingResourcePatternResolver();
String extensionWithDot = extension.startsWith(".") ? extension : "." + extension;
Resource[] resources = loader.getResources("classpath*:" + prefix + "*" + extensionWithDot);
List activeProfilesList = new ArrayList();
activeProfilesList.add(EMPTY_PROFILE);
activeProfilesList.addAll(List.of(activeProfiles));
return Stream.of(resources)
.map(resource -> new ProfiledResource(resource, extractProfile(resource.getFilename())))
.filter(profiledResource -> activeProfilesList.contains(profiledResource.profile))
.sorted(Comparator.comparingInt(pr -> activeProfilesList.indexOf(pr.profile)))
.map(ProfiledResource::resource)
.toList();
}
private static String filenameWithoutExtension(String filename) {
return filename.substring(0, filename.lastIndexOf("."));
}
private static String extractProfile(String filename) {
String filenameWithoutExtension = filenameWithoutExtension(filename);
String[] split = filenameWithoutExtension.split("-", -1);
return split.length > 1 ? split[split.length - 1] : EMPTY_PROFILE;
}
}
Код: Выделить всё
List resources = ResourceLoaderUtil.getResources("my-custom-folder/my-custom-file", ".yml", environment.getActiveProfiles());
for (Resource resource : resources) {
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
PropertySource propertySources = loader.load("some-name", resource).getFirst();
// how to merge propertySources ?
}
Есть ли лучший способ загрузить все файлы yaml и переопределить свойства в соответствии с текущими активными профилями Spring?
>
Подробнее здесь: https://stackoverflow.com/questions/785 ... ng-profile
Мобильная версия