(Used when connecting to the database) spring of using an external property file

(1) configuration in the configuration file Bean, sometimes mixed deployment details in the configuration where the bean (e.g., file path, data source configuration information, etc.), and these details are actually needed to deploy and Bean separate files.

(2) spring provides BeanFactory PropertyPlaceHolderConfigure of a postprocessor. This processor allows the user to part of the configuration file is transferred to the Bean properties file, in the form of bean can be used for the configuration file $ {var} variable. PropertyPlaceHolderConfigre loaded property from the property file, and use these properties to replace the variable.

(3) spring also allows the use $ {propName} in the attribute file, to achieve mutual references between the properties.

The drive mysql c3p0 and added to the build path.

First, be sure to start mysql service, and then introduced into the context namespace in the configuration file.

db.properties

user=root
password=123456
jdbcUrl=jdbc:mysql:///test
driverClass=com.mysql.jdbc.Driver

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/spring-context-4.3.xsd http://www.springframework.org/schema/context " > 
    ! <- Import properties file -> 
    < context: Property -placeholder LOCATION = "CLASSPATH: the db.properties" />
    
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 使用外部化属性文件的属性 -->
        <property name="user" value="${user}"></property>
        <property name="password" value="${password}"></property>
        <property name="jdbcUrl" value="${jdbcUrl}"></property>
        <property name="driverClass" value="${driverClass}"></property>

    </bean>
    
</beans>

Main.java

package com.gong.spring.beans.properties;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public  class the Main {
     public  static  void main (String [] args) throws SQLException {
         // 1. Create spring IOC container object of 
        the ApplicationContext CTX = new new the ClassPathXmlApplicationContext ( "Beans-properties.xml" );
         // 2. obtaining from the container Bean instance 
        the DataSource the dataSource = (the DataSource) ctx.getBean ( "the dataSource" );
        System.out.println(dataSource.getConnection());
    }
}

When you see the output:

The configuration was successful. 

Guess you like

Origin www.cnblogs.com/xiximayou/p/12152636.html