zoukankan      html  css  js  c++  java
  • spring解析xml,yml配置文件

    1 解析xml文件

    xml配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
    <properties>
        <entry key="jdbc.driver">com.mysql.jdbc.Driver</entry>
        <entry key="jdbc.url">jdbc:mysql://localhost:3306/spring</entry>
        <entry key="jdbc.username">root</entry>
        <entry key="jdbc.password">123456</entry>
    </properties>
    

    添加注解@PropertySource("classpath:jdbc.xml")

    下面的2个图为它的执行流程

    image-20200916154101217

    image-20200916154212032

    但是不推荐xml,虽然结构比较清楚,但是规范太严格了,写起来也很麻烦。

    2 解析yml文件

    之前博客也写过简单的解析yml文件,那个是参考官网的,但是感觉没有这个灵活,具体如下:

    yml文件:

    jdbc:
      driver: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/spring
      username: root
      password: 123456
    

    pom.xml

            <!-- yaml解析器 https://mvnrepository.com/artifact/org.yaml/snakeyaml -->
            <dependency>
                 <groupId>org.yaml</groupId>
                 <artifactId>snakeyaml</artifactId>
                 <version>1.23</version>
            </dependency>
    

    主类:

    /**
     * @author WGR
     * @create 2020/9/16 -- 16:09
     */
    public class CustomerPropertySourceFactory implements PropertySourceFactory {
        @Override
        public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
            //1.创建yaml文件解析工厂
            YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
            //2.设置资源内容
            yaml.setResources(resource.getResource());
            //3.解析成properties文件
            Properties properties = yaml.getObject();
            //4.返回符合spring的PropertySource对象
            return name != null ? new PropertiesPropertySource(name, properties) : new PropertiesPropertySource(resource.getResource().getFilename(), properties);
        }
    }
    
    /**
     * @author WGR
     * @create 2020/9/14 -- 20:41
     */
    @Configuration
    @Import(JdbcConfig.class)
    //@PropertySource("classpath:jdbc.xml")
    @PropertySource(value="classpath:jdbc.yml",factory=CustomerPropertySourceFactory.class)
    public class SpirngIocConfigure {
    }
    
    

    测试:

    image-20200916164509937

  • 相关阅读:
    html5基础---canvas
    html5基础---h5特性
    JS常用知识点(一)
    微信小程序开发(一)基础知识学习
    关于C# winform唤起本地已安装应用程序(测试win10,win7可用)
    js原型链结构理解
    JS闭包应用场景之函数回调(含函数的调用个人理解)
    (十三)MySQL锁机制
    (十一)MVCC-多版本并发控制机制(转)
    jvm014-垃圾回收器
  • 原文地址:https://www.cnblogs.com/dalianpai/p/13679992.html
Copyright © 2011-2022 走看看