Spring 如何读取properties文件内容

http://hi.baidu.com/alizv/blog/item/d8cb2af4094662dbf3d38539.html

在现实工作中,我们常常需要保存一些系统配置信息,大家一般都会选择配置文件来完成,本文根据我工作中用到的读取properties配置文件的方法小小总结一下,主要叙述的是spring读取配置文件的方法。
   用spring读取配置文件,最典型的就是关于数据库的连接,下面就是一个例子:
   文件jdbc.properties:
-------------------------------------------------------------------------------------

      driverClassName com.mysql.jdbc.Driver
       url jdbc:mysql://localhost:3306/test
       username root
       password 1234
------------------------------------------------------------------------------------
引入spring的相关jar包,在applicationContext.xml中配置:
-------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
           <value>src/jdbc.properties</value>
</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 id="dao" class="com.zh.model.DataDAO">
   <property name="datasource">
     <ref local="datasource"/>
   </property>
</bean>

</beans>
-----------------------------------------------------------------------------------------
DataDAO.java

package com.zh.model;

import javax.sql.DataSource;

public class DataDAO {
private DataSource datasource;

public DataSource getDatasource() {
return datasource;
}

public void setDatasource(DataSource datasource) {
this.datasource = datasource;
}

}


------------------------------------------------------------------------------------
测试连接是否成功,test.java
package com.zh.logic;

import java.sql.Connection;

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

import com.zh.model.DataDAO;

public class test {
public static void main(String [] args){
   try{
   String[] path = {"src/applicationContext.xml"};
   ApplicationContext ctx = new FileSystemXmlApplicationContext(path);

   DataDAO dao = (DataDAO)ctx.getBean("dao");
   Connection con = dao.getDatasource().getConnection();
   System.out.println(con.isClosed());
   //System.out.print(dao.getName());
   }catch(Exception ex){
   ex.printStackTrace();
     }
   }
}
-------------------------------------------------------------------------------------
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"));
--------------------------------------------------------------------------------------
上面介绍了读取properties的内容,现实中我们还有可能要修改文件的内容,下面就看下怎么修改properties的内容,文件还是上面那个:
package com.zh.logic;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;

public class TestRead {
    
public void read(){
   try {
    InputStream in = this.getClass().getClassLoader().getResourceAsStream("config/host.properties");
    Properties p = new Properties();
    p.load(in);
    //p.list(System.out);
      
    System.out.println(p.getProperty("ip")+","+p.getProperty("username")+","+p.getProperty("pwd"));
   } catch (Exception e) {
    e.printStackTrace();
   }
}

public void update(String path){
    try{
     Properties p = new Properties();
     FileInputStream in = new FileInputStream(path);
     p.load(in);
     FileOutputStream out = new FileOutputStream(path);
    
     p.setProperty("ip","1234567");
     p.store(out,"ip update");
     //p.save(out,"ip updated");
    }catch(Exception ex){
     ex.printStackTrace();
    }
}
public static void main(String[] args){
   TestRead td = new TestRead();
   td.read();
   td.update("config/host.properties");
   td.read();
}
}
可以看见修改之前的和修改之后的内容有改变;在上面有点要注意的:
        
FileInputStream in = new FileInputStream(path);
p.load(in);
FileOutputStream out = new FileOutputStream(path);
就是p.load(in);要写在FileOutputStream out = new FileOutputStream(path);之前,不然的话,修改后的文件内容就成了ip=1234567,而port=8080这句被覆盖了;什么愿意大家自己想想吧;

上面介绍了两中读取properties文件的方法,希望对大家有帮助........

### 回答1: Spring可以通过`PropertyPlaceholderConfigurer`来读取properties文件。 1. 在Spring配置文件中添加`PropertyPlaceholderConfigurer`的bean: ```xml <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:config.properties</value> </list> </property> </bean> ``` 2. 在properties文件中定义属性: ```properties jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=123456 ``` 3. 在Spring配置文件中使用属性: ```xml <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> ``` 这样就可以通过Spring读取properties文件中的属性了。 ### 回答2: Spring 是一个广泛使用的框架,受欢迎的一个原因是其简化了很多任务。其中之一就是读取 properties 文件。在 Spring 中,我们不必自己编写代码从文件读取属性。我们可以利用 Spring 的功能来自动读取属性,使得我们可以更加专注于应用程序的业务逻辑,并且遵循 Spring 管理原则。 Spring 提供了多种读取 properties 文件的方式。下面是其中的几种常见方式: 1. 使用 @Value 注解 @Value 注解本质上将属性文件的值注入到我们的 Java 类中。例如,我们可以在 Spring 的配置文件中定义以下属性值: application.properties ```properties app.name=My Application app.version=1.0 ``` 然后在我们的 Java 类中,在需要的属性前面加上 @Value 注解即可。 ```java @Component public class MyComponent { @Value("${app.name}") private String appName; @Value("${app.version}") private String appVersion; // ... } ``` 2. 使用 PropertySourcesPlaceholderConfigurer PropertySourcesPlaceholderConfigurer 是一个特殊的 bean,它读取属性文件并将属性值注入到其他 bean 中。配置方式如下: ```xml <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:/application.properties</value> </list> </property> </bean> ``` 然后,在 Java 类中可以使用 @Value 注解获取属性值。 3. 配置文件的统一管理 Spring 还提供了一个功能来统一管理配置文件。每个应用程序可能需要多个配置文件,所以 Spring 提供了一种方法来将这些配置文件合并为一个层次结构。这种方式称为 “Environment Abstraction”,它允许应用程序使用一组由多个配置文件组成的 “属性源”。 ```java @Configuration @PropertySource("classpath:/application.properties") public class AppConfig { @Autowired Environment env; @Bean public MyComponent myComponent() { MyComponent component = new MyComponent(); component.setAppName(env.getProperty("app.name")); component.setAppVersion(env.getProperty("app.version")); return component; } } ``` 以上是 Spring 读取 properties 文件的常见方式。开发者可以根据自己的需求选择不同的方式。无论选择哪种方式,Spring 已经为我们创建了属性文件读取的底层机制和简化方式,使得我们更加便利地开发。 ### 回答3: Spring读取properties文件是很常见的操作,通常我们会在配置文件中声明需要读取文件路径,并通过注入的方式将文件中的内容读取Spring的环境中。以下是更详细的步骤: 1. 确定properties文件的存储位置和名称。可以将其放置在classpath下或者指定文件路径。这里假设放在classpath下,文件名为config.properties。 2. 在Spring的配置文件中使用以下语句引用这个properties文件: ``` <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:config.properties</value> </list> </property> </bean> ``` 这里使用了Spring提供的“PropertyPlaceholderConfigurer”类。这个类允许我们将properties文件内容注入到Spring的环境中。 3. 在需要读取properties文件的类中注入这个“PropertyPlaceholderConfigurer”对象,并使用以下语句读取其中的值: ``` @Value("${key}") private String value; ``` 其中,key是properties文件中的键名,value则为其对应的值。 另外,还可以通过“ResourceBundleMessageSource”类直接读取properties文件中的文本资源,例如: ``` ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("config"); String message = messageSource.getMessage("key", null, Locale.getDefault()); ``` 这里使用了Spring提供的“ResourceBundleMessageSource”类,将properties文件中的文本资源转换为字符串类型的message。 总之,读取properties文件Spring开发中一个比较基础的操作,熟练掌握此技能可以提高代码开发效率,并且为系统开发提供清晰的配置方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值