zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Spring读取Yaml

Spring 读取 yaml
2023-09-14 09:00:25 时间
public class YamlUtils { private static final Logger logger = LogManager.getLogger(YamlUtils.class); public stat

To use Maven: org.springframework:spring-beans:4.3.2.RELEASE2

public class YamlUtils {

 private static final Logger logger = LogManager.getLogger(YamlUtils.class);

 public static Map String, Object yaml2Map(String yamlSource) {

 try {

 YamlMapFactoryBean yaml = new YamlMapFactoryBean();

 yaml.setResources(new ClassPathResource(yamlSource));

 return yaml.getObject();

 } catch (Exception e) {

 logger.error("Cannot read yaml", e);

 return null;

 public static Properties yaml2Properties(String yamlSource) {

 try {

 YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();

 yaml.setResources(new ClassPathResource(yamlSource));

 return yaml.getObject();

 } catch (Exception e) {

 logger.error("Cannot read yaml", e);

 return null;

}
public class TestYamlUtils {

 private static final Logger logger = LogManager.getLogger(TestYamlUtils.class);

 @Test

 public void testYaml2Map() {

 Map String, Object map = YamlUtils.yaml2Map("neiwai.yml");

 Assert.assertNotNull(map);

 map.forEach((k, v) - {

 logger.info("k={},v={}", k, v);

 @Test

 public void testYaml2Properties() {

 Properties prop = YamlUtils.yaml2Properties("neiwai.yml");

 Assert.assertNotNull(prop);

 prop.forEach((k, v) - {

 logger.info("k={},v={}", k, v);

}

Spring五大类注解读取存储Bean对象 我们之前注册bean是通过在xml配置文件中,通过键值对的方式注册bean对象! 显然这种方式很麻烦,注册一个对象,就要添加一项! 有没有什么好的方式可以让spring直接去注册对象! 我们可以直接在配置文件配置好 spring下你要注册对象的包时那个! 当spring启动后,spring就会将bean对象自动注册!
Sring源码解析(一)Spring是怎么读取配置Xml文件的 1#Spring读取配置文件 ##Document 在XmlBeanDefinitionReader.doLoadBeanDefinitions(InputSource inputSource, Resource resource)方法中将Xml文件转换成Document对象;Document doc = doLoadDocument(inputSource, resource);
阿里特邀专家徐雷Java Spring Boot开发实战系列课程(第18讲):制作Java Docker镜像与推送到DockerHub和阿里云Docker仓库 立即下载