文件jdbc.properties:
-------------------------------------------------------------------------------------
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=1234
------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=1234
------------------------------------------------------------------------------------
引入spring的相关jar包,在applicationContext.xml中配置
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>src/jdbc.properties</value> //通过PropertyPlaceholderConfigurer 读取配置文件
</property>
</bean>
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${driverClassName}</value> //${} 这种格式使用配置文件中的数据
</property>
<property name="url">
<value>${url}</value>
</property>
<property name="username">
<value>${username}</value>
</property>
<property name="password">
<value>${password}</value>
</property>
</bean>
</bean>
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${driverClassName}</value> //${} 这种格式使用配置文件中的数据
</property>
<property name="url">
<value>${url}</value>
</property>
<property name="username">
<value>${username}</value>
</property>
<property name="password">
<value>${password}</value>
</property>
</bean>
方式2:用java.util.Properties这个类来读取
比如,我们构造一个ipConfig.properties来保存服务器ip地址和端口,如:
ip=192.168.0.1
port=8080
--------------------------------------------------------------------------------------
ip=192.168.0.1
port=8080
--------------------------------------------------------------------------------------
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ipConfig.properties");
Properties p = new Properties();
try{
p.load(inputStream);
} catch (IOException e1){
e1.printStackTrace();
}
System.out.println("ip:"+p.getProperty("ip")+",port:"+p.getProperty("port"));
--------------------------------------------------------------------------------------
Properties p = new Properties();
try{
p.load(inputStream);
} catch (IOException e1){
e1.printStackTrace();
}
System.out.println("ip:"+p.getProperty("ip")+",port:"+p.getProperty("port"));
--------------------------------------------------------------------------------------