zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    C#自定义控件的开发:Pin和Connector
    C# 调用第三方DLL完整实例
    利用微软Speech SDK 5.1开发语音识别系统主要步骤
    如何在Android中使用OpenCV
    VS 2012单元测试和测试资源管理器
    .NET Reflector插件FileDisassembler还原源码
    根据powerdesigner的OO模型生成C#代码
    SQLServer2008设置开启INTERNET远程连接
    Kudu-压缩
    kudu的读取数据流程
  • 原文地址:https://www.cnblogs.com/jeremy-blog/p/4024889.html
Copyright © 2011-2022 走看看