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

  • 相关阅读:
    免费馅饼(HDU 1176 DP)
    搬寝室(HDU 1421 DP)
    FatMouse's Speed(HDU LIS)
    Bone Collector II(HDU 2639 DP)
    Palindrome(POJ 1159 DP)
    Proud Merchants(POJ 3466 01背包+排序)
    树的最大独立集
    Roads in the North(POJ 2631 DFS)
    Starship Troopers(HDU 1011 树形DP)
    Strategic game(POJ 1463 树形DP)
  • 原文地址:https://www.cnblogs.com/dalianpai/p/13679992.html
Copyright © 2011-2022 走看看