• Spring 从入门到精通 (九) 配置文件参数化


    关键词:Spring | 配置文件 | 参数化

    本专栏通过理论和实践相结合,系统学习框架核心思想及简单原理,原创不易,如果觉得文章对你有帮助,点赞收藏支持博主 ✨

    在这里插入图片描述

    一、概念

    配置文件参数化是指把Spring配置文件中经常需要修改的字符串信息,单独提取转移到一个小配置文件中。

    二、有经常修改的配置吗?

    有啊,比如数据库相关的配置

    三、为什么要转移?

    有人又称Spring项目为 配置地狱 ,其实就是真实项目Spring配置可能会达到几千行甚至更多,此时去修改一些参数,比如数据库配置相关的,就非常不利于维护,因此,希望能把它单独抽取出来,放在一个单独的小配置文件中(properties),利于项目维护。

    四、开发

    开发思路

    首先准备好要转移常用字符串的小配置文件,然后通过配置告诉spring咱使用了小配置文件,并指定是哪一个,通过一些特殊配置完成开发。

    首先,准备一个小的配置文件(properties),名字没要求,位置没要求

    driverClassName = com.mysql.jdbc.Driver
    url = jdbc:mysql://localhost:3306/zhou?useSSL=false
    username = root
    password = root
    
    • 1
    • 2
    • 3
    • 4

    Spring中配置
    ,这里注意使用了classpath,这里的这个是什么意思呢?就是指类路径,类路径又是哪呢,哈哈,这个问题问得好,这就要根据情况说了,在Maven项目中,根据Maven的目录和打包机制,会将Java目录和resources目录打包在同一目录下,这也就是所谓的classpath类路径,具体的可以看打包后的目录结构如下:

    在这里插入图片描述

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:property-placeholder location="classpath:db.properties"/>
    
        <bean id="conn" class="factorybean.ConnectionFactoryBean">
            <property name="driverClassName" value="${driverClassName}"/>
            <property name="url" value="${url}"/>
            <property name="username" value="${username}"/>
            <property name="password" value="${password}"/>
        bean>
    
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    测试,尝试获取连接对象,如果成功获取,说明配置文件参数化成功,否则失败。

    @Test
    public void t7() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("newspring.xml");
        Connection conn = (Connection) context.getBean("conn");
        System.out.println(conn);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    成功拿到,没有问题

    com.mysql.jdbc.JDBC4Connection@19b2141
    
    • 1

    五、写在最后

    座右铭:不要在乎别人如何看你,要在乎你自己如何看未来,看梦想,看世界…!

    一起学习的可以私信博主或添加博主微信哦。

    专栏:订阅专栏 ✅
    关注:关注博主 🆙

  • 相关阅读:
    ubuntu安装tensorflow(cpu版)教程
    vite项目启动use `--host` to expose
    普乐蛙景区文旅VR体验馆项目沉浸式文旅体验
    项目分享19
    MATLAB遗传算法求解生鲜货损制冷时间窗碳排放多成本车辆路径规划问题
    数据可视化时代,为智慧城市建设添彩_光点科技
    C++一行代码实现任意系统函数Hook
    【Rust基础②】流程控制、模式匹配
    java计算机毕业设计郑工社团交流服务信息平台源码+mysql数据库+系统+lw文档+部署
    在vue项目里面使用index.ts进行统一导出
  • 原文地址:https://blog.csdn.net/m0_53321320/article/details/125885785