– Start
点击此处观看本系列配套视频。
我们开发软件时,通常有三个环境,开发环境(dev),测试环境(test)和生产环境(prod),不同的环境连接不同的数据库,我们该怎么配置呢?
首先我们可以定义三个 properties 文件,将不同环境的数据库的配置在里面。
system.dev.properties
system.test.properties
system.prod.properties
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://dev:9002
jdbc.username=sa
jdbc.password=root
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://test:9002
jdbc.username=sa
jdbc.password=root
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root
然后我们可以在 Spring XML 配置文件中配置注册我们的 properties,然后通过${xx} 方式引用属性。
<?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.3.xsd">
<!--
注册 properties 文件,需要引入 context 命名空间
-->
<context:property-placeholder location="classpath:shangbo/spring/example43/system.${env}.properties"/>
<!--
也可以使用如下的方式注册 p