• 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
  • 相关阅读:
    [CCS] 没有Runtime Object View(ROV)怎么办?
    前端 nginx 部署项目
    Docker in Docker(DinD)原理与实践
    Docker快速部署Tomcat
    《QT实用小工具·五十八》模仿VSCode的可任意拖拽的Tab标签组
    Linux如何安装JDK?Linux如何安装JDK1.8?FinalShell如何上传文件到Linux?
    python 第五章
    基于SSM的酒店客房管理系统
    python+nodejs+vue.js在线英语学习网站
    python实现全向轮EKF_SLAM
  • 原文地址:https://blog.csdn.net/m0_50744075/article/details/126254784