java读取.properties配置文件的几种方法

一.通过jdk提供的java.util.Properties类

        此类继承自java.util.HashTable,即实现了Map接口,所以,可使用相应的方法来操作属性文件,但不建议使用像put、putAll这 两个方法,因为put方法不仅允许存入String类型的value,还可以存入Object类型的。因此java.util.Properties类提 供了getProperty()和setProperty()方法来操作属性文件,同时使用store或save(已过时)来保存属性值(把属性值写 入.properties配置文件)。在使用之前,还需要加载属性文件,它提供了两个方法:load和loadFromXML。

        load有两个方法的重载:load(InputStream inStream)、load(Reader reader),所以,可根据不同的方式来加载属性文件。

        可根据不同的方式来获取InputStream,如:

1.通过当前类加载器的getResourceAsStream方法获取下载地址   

  1. InputStream inStream = TestProperties.class.getClassLoader().getResourceAsStream("test.properties");  

2.从文件获取

  1. InputStream inStream = new FileInputStream(new File("filePath"));  

3.也是通过类加载器来获取,和第一种一样

  1. InputStream in = ClassLoader.getSystemResourceAsStream("filePath");  

4.在servlet中,还可以通过context来获取InputStream

  1. InputStream in = context.getResourceAsStream("filePath");  

5.通过URL来获取

  1. URL url = new URL("path");  
  2. InputStream inStream = url.openStream();  

读取方法如下:

  1. Properties prop = new Properties();    
  2. prop.load(inStream);    
  3. String key = prop.getProperty("username");    
  4. //String key = (String) prop.get("username");  

 

二.通过java.util.ResourceBundle类读取

        这种方式比使用Properties要方便一些。

1.通过ResourceBundle.getBundle()静态方法来获取

        ResourceBundle是一个抽象类,这种方式来获取properties属性文件不需要加.properties后缀名,只需要文件名即可。

  1. ResourceBundle resource = ResourceBundle.getBundle("com/mmq/test");//test为属性文件名,放在包com.mmq下,如果是放在src下,直接用test即可    
  2. String key = resource.getString("username");  

2.从InputStream中读取

        获取InputStream的方法和上面一样,不再赘述。

  1. ResourceBundle resource = new PropertyResourceBundle(inStream);  

        注意:在使用中遇到的最大的问题可能是配置文件的路径问题,如果配置文件入在当前类所在的包下,那么需要使用包名限定, 如:test.properties入在com.mmq包下,则要使用com/mmq/test.properties(通过Properties来获 取)或com/mmq/test(通过ResourceBundle来获取);属性文件在src根目录下,则直接使用test.properties 下载地址   或test即可。

 

三.实例

ResourceLoader.java

  1. package com.bijian.study;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.util.HashMap;  
  6. import java.util.Map;  
  7. import java.util.Properties;  
  8.   
  9. public final class ResourceLoader {  
  10.   
  11.     private static ResourceLoader loader = new ResourceLoader();  
  12.     private static Map<String, Properties> loaderMap = new HashMap<String, Properties>();  
  13.   
  14.     private ResourceLoader() {  
  15.     }  
  16.   
  17.     public static ResourceLoader getInstance() {  
  18.         return loader;  
  19.     }  
  20.       
  21.     public Properties getPropFromProperties(String fileName) throws Exception {  
  22.           
  23.         Properties prop = loaderMap.get(fileName);  
  24.         if (prop != null) {  
  25.             return prop;  
  26.         }  
  27.         String filePath = null;  
  28.         String configPath = System.getProperty("configurePath");  
  29.   
  30.         if (configPath == null) {  
  31.             filePath = this.getClass().getClassLoader().getResource(fileName).getPath();  
  32.         } else {  
  33.             filePath = configPath + "/" + fileName;  
  34.         }  
  35.         prop = new Properties();  
  36.         prop.load(new FileInputStream(new File(filePath)));  
  37.   
  38.         loaderMap.put(fileName, prop);  
  39.         return prop;  
  40.     }  
  41. }  

PropertiesUtil.java

  1. package com.bijian.study;  
  2.   
  3. import java.util.Properties;  
  4. import java.util.concurrent.ConcurrentHashMap;  
  5. import java.util.concurrent.ConcurrentMap;  
  6.   
  7. /** 
  8.  * 用ConcurrentMap来缓存属性文件的key-value 
  9.  */  
  10. public class PropertiesUtil {  
  11.       
  12.     private static ResourceLoader loader = ResourceLoader.getInstance();  
  13.     private static ConcurrentMap<String, String> configMap = new ConcurrentHashMap<String, String>();  
  14.     private static final String DEFAULT_CONFIG_FILE = "test.properties";  
  15.   
  16.     private static Properties prop = null;  
  17.   
  18.     public static String getStringByKey(String key, String propName) {  
  19.         try {  
  20.             prop = loader.getPropFromProperties(propName);  
  21.         } catch (Exception e) {  
  22.             throw new RuntimeException(e);  
  23.         }  
  24.         key = key.trim();  
  25.         if (!configMap.containsKey(key)) {  
  26.             if (prop.getProperty(key) != null) {  
  27.                 configMap.put(key, prop.getProperty(key));  
  28.             }  
  29.         }  
  30.         return configMap.get(key);  
  31.     }  
  32.   
  33.     public static String getStringByKey(String key) {  
  34.         return getStringByKey(key, DEFAULT_CONFIG_FILE);  
  35.     }  
  36.   
  37.     public static Properties getProperties() {  
  38.         try {  
  39.             return loader.getPropFromProperties(DEFAULT_CONFIG_FILE);  
  40.         } catch (Exception e) {  
  41.             e.printStackTrace();  
  42.             return null;  
  43.         }  
  44.     }  
  45. }  

Constant.java

  1. package com.bijian.study;  
  2.   
  3. public class Constant {  
  4.       
  5.     public static final String TEST = PropertiesUtil.getStringByKey("test""test.properties");  
  6. }  

Main.java

  1. package com.bijian.study;  
  2.   
  3. public class Main {  
  4.   
  5.     public static void main(String[] args) {  
  6.           
  7.         System.out.println(Constant.TEST);  
  8.     }  
  9. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot读取application.properties的值的方式有多种方法。一种常用的方式是通过使用@Value注解来注入属性值。可以在需要使用属性值的字段、方法的参数、方法的返回值上添加@Value注解,并指定要注入的属性的键名。例如,可以使用@Value("${spring.rabbitmq.host}")来注入application.properties文件中的spring.rabbitmq.host属性的值。这样,在程序运行时,Spring Boot会自动读取属性文件中的值,并将其注入到相应的位置。 另一种方式是使用PropertiesLoaderUtils类来读取属性文件的值。首先,需要导入java.util.Properties和org.springframework.core.io.support.PropertiesLoaderUtils类。然后,可以使用PropertiesLoaderUtils的loadProperties方法来加载属性文件,然后使用getProperty方法获取具体的属性值。例如,可以使用Properties properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource("application.properties"))来加载application.properties文件,然后使用properties.getProperty("spring.rabbitmq.host")来获取spring.rabbitmq.host属性的值。 总结起来,Spring Boot提供了多种方式来读取application.properties文件的值,可以根据具体的需求选择适合的方式来获取属性值。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Spring Boot中配置文件application.properties使用](https://download.csdn.net/download/weixin_38672800/12765190)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [SpringBoot获得application.properties中数据的几种方式](https://blog.csdn.net/m0_67393686/article/details/124421983)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [SpringBoot读取application.properties配置文件](https://blog.csdn.net/watson2017/article/details/124732267)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值