-
-
Save g00glen00b/9e052d34f461bf761e5e6c3892febf79 to your computer and use it in GitHub Desktop.
Automatically add a prefix to properties in Spring Boot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.demo; | |
import org.springframework.core.env.PropertiesPropertySource; | |
import org.springframework.core.env.PropertySource; | |
import org.springframework.core.io.support.EncodedResource; | |
import org.springframework.core.io.support.PropertiesLoaderUtils; | |
import org.springframework.core.io.support.PropertySourceFactory; | |
import java.io.IOException; | |
import java.util.Properties; | |
import java.util.Set; | |
public class PrefixPropertySourceFactory implements PropertySourceFactory { | |
@Override | |
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { | |
String resultName = name != null ? name : getNameForResource(resource); | |
String prefix = getFilenameWithoutExtension(resource); | |
Properties resultProperties = getPropertiesWithPrefix(sourceProperties, prefix); | |
return new PropertiesPropertySource(resultName, resultProperties); | |
} | |
private static Properties getPropertiesWithPrefix(EncodedResource resource, String prefix) throws IOException { | |
Properties sourceProperties = PropertiesLoaderUtils.loadProperties(resource); | |
return sourceProperties | |
Set<String> propertyNames = sourceProperties.stringPropertyNames(); | |
Properties resultProperties = new Properties(); | |
sourceProperties.forEach((key, value) -> resultProperties.put(prefix + "." + key, value)); | |
propertyNames.forEach(propertyName -> resultProperties.put( | |
prefix + "." + propertyName, | |
sourceProperties.getProperty(propertyName)) | |
); | |
return resultProperties; | |
} | |
private static String getFilenameWithoutExtension(EncodedResource resource) { | |
String filename = resource.getResource().getFilename(); | |
int lastPositionOfDot = filename.lastIndexOf('.'); | |
if (lastPositionOfDot > 0) return filename.substring(0, lastPositionOfDot); | |
else return filename; | |
} | |
private static String getNameFromResource(EncodedResource resource) { | |
String description = resource.getResource().getDescription(); | |
if (!description.isBlank()) return description; | |
String className = resource.getClass().getSimpleName(); | |
int hashCode = System.identityHashCode(resource); | |
return className + "@" + hashCode; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment