Spring-Bean Configuration - Using External Properties File
So you can get the key-value of the configuration file through the @value annotation to generate a configuration file bean. A way to use beans directly in code.
• When configuring beans in configuration files, it is sometimes necessary to mix system deployment details (eg file paths, data source configuration information, etc.) into the bean configuration. These deployment details actually need to be separated from the bean configuration
• Spring provides a BeanFactory post-processor for PropertyPlaceholderConfigurer, which allows users to move part of the Bean configuration to the properties file. Variables in the form of ${var} can be used in the Bean configuration file, and the PropertyPlaceholderConfigurer is derived from the property Load properties in the file, and use those properties to replace variables.
• Spring also allows the use of ${propName} in property files to enable mutual references between properties.
Case: Use db.properties to configure the information for connecting to the database, obtain the information through the bean configuration file, and then create a data source;
The db.properties configuration information is as follows:
- user=scott
- password=tiger
- dirverClass=oracle.jdbc.driver.OracleDriver
- jdbcUrl=jdbc\:oracle\:thin\:@localhost\:1521\:oracl
- <?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">
- <!-- Import properties file -->
- <context:property-placeholder location="classpath:db.properties"/>
- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
- <!-- Use properties from external properties file -->
- <property name="user" value="${user}"></property>
- <property name="password" value="${password}"></property>
- <property name="driverClass" value="${dirverClass}"></property>
- <property name="jdbcUrl" value="${jdbcUrl}"></property>
- </bean>
- </beans>
- ApplicationContext axt = new ClassPathXmlApplicationContext("applicationContext_properties.xml");
- DataSource dataSource = (DataSource)axt.getBean("dataSource");
- System.out.println(dataSource.getConnection());