• Spring---Bean使用外部属性文件


    在配置文件里配置 Bean 时, 有时需要在 Bean 的配置里混入系统部署的细节信息(例如: 文件路径, 数据源配置信息等). 而这些部署细节实际上需要和 Bean 配置相分离
    Spring 提供了一个 PropertyPlaceholderConfigurer 的 BeanFactory 后置处理器, 这个处理器允许用户将 Bean 配置的部分内容外移到属性文件中. 可以在 Bean 配置文件里使用形式为 ${var} 为变量赋值, PropertyPlaceholderConfigurer 从属性文件里加载属性, 并使用这些属性来替换变量.
    Spring 还允许在属性文件中使用 ${propName},以实现属性之间的相互引用。

    Bean使用外部属性文件实现步骤(以配置c3p0数据源为例)

      1创建c3p0外部属性文件db.properties(采用键值对的方式)

    user=root
    password=1230
    driverClass=com.mysql.jdbc.Driver
    jdbcUrl=jdbc:mysql://localhost:3306/test

     2Spring4.0后是使用Context命名空间来配置的,所以需要导入Context命名空间:

      
      

    3在配置文件中配置外部文件,和c3p0的Bean实例,代码如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <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 http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    
        <context:property-placeholder location="com/jeremy/spring/properties/c3po.properties"/>
    
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="user" value="${user}"></property>
            <property name="password" value="${password}"></property>
            <property name="driverClass" value="${driverClass}"></property>
            <property name="jdbcUrl" value="${jdbcUrl}"></property>
        </bean>
    
    
    </beans>
  • 相关阅读:
    mysql索引
    springboot mybatis 后台框架平台 shiro 权限 集成代码生成器
    java 企业网站源码模版 有前后台 springmvc SSM 生成静态化
    java springMVC SSM 操作日志 4级别联动 文件管理 头像编辑 shiro redis
    activiti工作流的web流程设计器整合视频教程 SSM和独立部署
    .Net Core中的ObjectPool
    文件操作、流相关类梳理
    .Net Core中的配置文件源码解析
    .Net Core中依赖注入服务使用总结
    消息中间件RabbitMQ(一)
  • 原文地址:https://www.cnblogs.com/jeremy-blog/p/4024889.html
Copyright © 2020-2023  润新知