zoukankan      html  css  js  c++  java
  • Spring-Bean配置-使用外部属性文件(转)

    Spring-Bean配置-使用外部属性文件

    所以可以通过@value注解获取配置文件的key-value,生成一个配置文件bean。用以在代码中直接使用bean的方式。

    •在配置文件里配置Bean时,有时需要在Bean的配置里混入系统部署的细节信息(例如:文件路径,数据源配置信息等).而这些部署细节实际上需要和Bean配置相分离
    •Spring 提供了一个PropertyPlaceholderConfigurer的BeanFactory后置处理器,这个处理器允许用户将Bean配置的部分内容外移到属性文件中.可以在Bean配置文件里使用形式为${var} 的变量,PropertyPlaceholderConfigurer从属性文件里加载属性,并使用这些属性来替换变量.
    •Spring 还允许在属性文件中使用${propName},以实现属性之间的相互引用。
    案例:使用db.properties配置连接数据库的信息,通过bean配置文件获取该信息,然后建立数据源;
    db.properties配置信息如下:
    [plain] view plain copy
     
    1. user=scott  
    2. password=tiger  
    3. dirverClass=oracle.jdbc.driver.OracleDriver  
    4. jdbcUrl=jdbc:oracle:thin:@localhost:1521:oracl  
    beans配置文件:applicationContext_properties.xml
    [html] view plain copy
     
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <beans xmlns="http://www.springframework.org/schema/beans"  
    3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    4.     xmlns:context="http://www.springframework.org/schema/context"  
    5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
    6.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">  
    7.       
    8.     <!-- 导入属性文件 -->  
    9.     <context:property-placeholder location="classpath:db.properties"/>  
    10.       
    11.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">  
    12.         <!-- 使用外部属性文件的属性 -->  
    13.         <property name="user" value="${user}"></property>  
    14.         <property name="password" value="${password}"></property>  
    15.         <property name="driverClass" value="${dirverClass}"></property>  
    16.         <property name="jdbcUrl" value="${jdbcUrl}"></property>  
    17.     </bean>  
    18. </beans>  
    建立数据源代码如下:
    [java] view plain copy
     
    1. ApplicationContext axt = new ClassPathXmlApplicationContext("applicationContext_properties.xml");  
    2. DataSource dataSource = (DataSource)axt.getBean("dataSource");  
    3. System.out.println(dataSource.getConnection());  
  • 相关阅读:
    AndroidStudio制作个人资料界面模块以及SQLite数据库的使用
    掌握这13个MySQL索引知识点,让你面试通过率翻倍
    获取数据表最后最后访问,修改,更新,扫描时间
    一本彻底搞懂MySQL索引优化EXPLAIN百科全书
    Win10系统下的MySQL5.7.24版本(解压版)详细安装教程
    解决beego在ubuntu下连接mysql与重置mysql密码
    在Windows上安装MySQL
    docker~dockertoolbox的加速器
    Git 安装 on centos7
    centos7.x中安装SQL Server
  • 原文地址:https://www.cnblogs.com/panxuejun/p/8969863.html
Copyright © 2011-2022 走看看