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

  • 相关阅读:
    网页媒体播放利器
    iframe截取网站部分内容实现思路及代码
    网站如何添加访客统计代码
    Javascript写入txt和读取txt文件示例
    常见JS挂马方法及如何防止网站被黑客挂马?
    最新挂木马的10大操作方法
    Javascript教程:js异步模式编程的4种解决方法
    JavaScript对象属性的基础教程指南
    jsp中的JSTL与EL表达式用法
    Java 连接 SqlServer工具类
  • 原文地址:https://www.cnblogs.com/dalianpai/p/13679992.html
Copyright © 2011-2022 走看看