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

  • 相关阅读:
    【WIN32API&DAPI】窗口相关函数
    第十四章_安全性
    android实现gif图与文字混排
    Extjs 4.2 设置buttontext为中文
    HDU 5384 Danganronpa (AC自己主动机模板题)
    bzoj2938【Poi2000】病毒
    [Java开发之路](9)对象序列化与反序列化
    atitit.jndi的架构与原理以及资源配置and单元測试实践
    QueryError:Incorrect result size: expected 1, actual 0
    LightOJ 1070 Algebraic Problem (推导+矩阵高速幂)
  • 原文地址:https://www.cnblogs.com/dalianpai/p/13679992.html
Copyright © 2011-2022 走看看