zoukankan      html  css  js  c++  java
  • spring 使用外部属性文件

    概要:



    使用外部属性文件

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


    注冊PropertyPlaceholderConfigurer
    • Spring 2.0:

    • Spring2.5之后:可通过<context:property-placeholder>元素简化:
      • <beans>中添加centext Schema定义(context命名空间 )
      • 在配置文件里添加例如以下配置:



    实例代码具体解释:
    文件夹结构

    由于要连接数据源:所以要增加mysql和c3p0的jar包


    Main.java
    package com.coslay.beans.properties;
    
    import java.sql.SQLException;
    import javax.sql.DataSource;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Main {
    	public static void main(String[] args) throws SQLException {
    		ApplicationContext ctx = new ClassPathXmlApplicationContext(
    				"beans-properties.xml");
    
    		DataSource dataSource = (DataSource) ctx.getBean("dataSource");
    
    		System.out.println(dataSource.getConnection());
    	}
    }


    beans-properties.xml
    <?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="classpath:db.properties"/>
    
    
    	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    		<!-- 使用外部属性文件的属性 -->
    		<property name="user" value="root"></property>
    		<property name="password" value="root"></property>
    		<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    		<property name="jdbcUrl" value="jdbc:mysql:///test"></property>
    	</bean>
    </beans>
    

    db.properties

    user=root
    password=root
    driverclass=com.mysql.jdbc.Driver
    jdbcurl=jdbc:mysql:///test


  • 相关阅读:
    ViewPage显示Fragment集合实现左右滑动并且出现tab栏--第三方开源--SlidingTabLayout和SlidingTabStrip实现
    Fragment的创建以及与activity的参数传递
    (转)Android属性设置android:noHistory="true"
    【英语】20140820 生词
    【性能测试】基础笔记
    【自动化测试】Selenium
    【自动化测试】Xpath学习
    【自动化测试】PO思路
    【网络】js调试F12控制台学习
    【自动化测试】Selenium excel操作
  • 原文地址:https://www.cnblogs.com/jzssuanfa/p/6919944.html
Copyright © 2011-2022 走看看