• Spring框架——加载属性(properties)文件


    使用属性文件的好处

    1. 有效的减少硬编码(将配置信息直接写入Java代码中)

    2. 当应用程序的运行环境发生改变时,只需要修改属性文件,而不需要改变源码.提高了运维人员操作的便利性

    加载属性文件的方式

    使用注解方式

    以db.properties文件为例

    mysql.driver=com.mysql.cj.jdbc.Driver
    mysql.url=jdbc:mysql://localhost:3306/DBName?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
    mysql.user=root
    mysql.password=010220
    
    • 1
    • 2
    • 3
    • 4

    可以使用@PropertySource进行属性文件的加载
    @PropertySource的配置项有:

    1. ‘name’:字符串,设置属性配置的名称
    2. ‘value’:字符串数组,可以配置多个属性文件
    3. ‘ignoreResourceNotFount’:是个boolean值,默认为false.表示若找不到对应的属性文件是否进行忽略处理。默认若找不到对应的属性文件则抛出异常
    4. ‘encoding’:编码格式(字符集)
    package com.bean;
    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.PropertySource;
    
    /**
     * @author Una
     * @date 2022/8/9 20:07
     * @description:
     */
    @PropertySource(value = {"classpath:db.properties"},ignoreResourceNotFound = true)
    public class PropertiesScan {
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    测试时使用getEnvironment().getProperty()可获得

    import org.junit.Test;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    import static org.junit.Assert.*;
    
    /**
     * @author Una
     * @date 2022/8/9 20:08
     * @description:
     */
    public class PropertiesScanTest {
        @Test
        public void showProperties(){
            AnnotationConfigApplicationContext aac=new AnnotationConfigApplicationContext(PropertiesScan.class);
            String root=aac.getEnvironment().getProperty("mysql.root");
            System.out.println(root);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    使用XML方式加载属性文件

    在配置文件中直接加入字段

      <context:property-placeholder location="classpath:database-config.properties" ignore-resource-not-found="true"/>
    
    • 1
  • 相关阅读:
    【毕业设计】深度学习YOLO图像视频足球和人体检测 - python opencv
    人工智能在汽车业应用的五项挑战
    校内评奖评优|基于Springboot+Vue实现高校评优管理系统
    Linux下编译libevent源码
    Springboot 2.5.X框架解决跨域遇到的坑
    Java中循环删除list报错解析
    使用 SwiftUI 构建表单:综合指南
    【C++面向对象】13. 接口 / 抽象类*
    LLM开源小工具(基于代码库快速学习/纯shell调用LLM灵活管理系统)
    StatusBarManager中的相关标志位
  • 原文地址:https://blog.csdn.net/m0_50744075/article/details/126254784