The spring container before starting use of spring 1 reads the boot yaml, spring boot 2 reference stackoverflow.com/questions/5… Modify the
package cn.inusha.multi.utils;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.bind.PropertiesConfigurationFactory;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySources;
import org.springframework.core.env.SystemEnvironmentPropertySource;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/ * * *@author InuYasha
*/
public class YamlUtil {
public static <T> T readToObj(Resource resource, T target, String prefix) {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new PropertiesPropertySource(resource.getFilename(), readAsProperties(resource)));
return readToObjFromPropertySources(target, prefix, propertySources);
}
public static <T> T readToObjWithSystemProperties(Resource resource, T target, String prefix) {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new PropertiesPropertySource(resource.getFilename(), readAsProperties(resource)));
Map<String, Object> sources = new HashMap<>();
System.getProperties().forEach((key, value) -> {
sources.put(key.toString(), value);
});
propertySources.addFirst(new PropertiesPropertySource(resource.getFilename(), readAsProperties(resource)));
propertySources.addFirst(new SystemEnvironmentPropertySource("systemProperties", sources));
return readToObjFromPropertySources(target, prefix, propertySources);
}
public static <T> T readToObjFromPropertySources(T target, String prefix, PropertySources propertySources) {
Assert.notNull(target, "target cannot is null");
Assert.notNull(prefix, "prefix cannot is null");
Assert.notNull(propertySources, "propertySources cannot is null");
PropertiesConfigurationFactory<Object> factory = new PropertiesConfigurationFactory<Object>(
target);
factory.setPropertySources(propertySources);
factory.setIgnoreInvalidFields(true);
factory.setIgnoreUnknownFields(true);
factory.setIgnoreNestedProperties(false);
factory.setTargetName(prefix);
try {
factory.bindPropertiesToTarget();
} catch (Exception ex) {
throw new RuntimeException("Error reading YAML", ex);
}
return target;
}
public static Properties readAsProperties(Resource resource) {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource);
factory.afterPropertiesSet();
returnfactory.getObject(); }}Copy the code