spring 读取properties文件

本文详细介绍了如何在Spring框架中配置MySQL数据库连接,包括使用PropertyPlaceholderConfigurer读取配置文件和通过Java代码动态获取配置参数的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  文件jdbc.properties:
-------------------------------------------------------------------------------------
       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>

方式2:用java.util.Properties这个类来读取
比如,我们构造一个ipConfig.properties来保存服务器ip地址和端口,如:
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"));
--------------------------------------------------------------------------------------



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值