正如M. Deinum 所提到的,关键是YamlPropertiesFactoryBean 。
import org.springframework.beans.factory.config.YamlProcessor;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.MapConfigurationPropertySource;
import org.springframework.core.io.ClassPathResource;
import java.util.Properties;
public class PropertyLoader {
private static Properties properties;
private PropertyLoader() {}
public static Properties load(String... activeProfiles) {
if (properties == null) {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ClassPathResource("application.yml"));
factory.setDocumentMatchers((profile) -> YamlProcessor.MatchStatus.FOUND); // TODO filter on active profiles
factory.afterPropertiesSet();
properties = factory.getObject();
}
return properties;
}
public static <T> T value(String property, Class<T> target) {
load();
ConfigurationPropertySource propertySource = new MapConfigurationPropertySource(properties);
Binder binder = new Binder(propertySource);
return binder.bind(property.toLowerCase(), target).get();
}
}
PropertyLoader#value
然后可以像这样使用:
List<String> items = PropertyLoader.value("my.profile.items", List.class);