關於properties文件的讀取(Java/spring/springmvc/springboot)


一.Java讀取properties文件

1、基於ClassLoder讀取配置文件

注意:該方式只能讀取類路徑下的配置文件,有局限但是如果配置文件在類路徑下比較方便。

1 Properties properties = new Properties();
2 // 使用ClassLoader加載properties配置文件生成對應的輸入流
3 InputStream in = PropertiesMain.class.getClassLoader().getResourceAsStream("config/config.properties");
4 // 使用properties對象加載輸入流
5 properties.load(in);
6 //獲取key對應的value值
7 properties.getProperty(String key);

2、基於 InputStream 讀取配置文件

注意:該方式的優點在於可以讀取任意路徑下的配置文件

1 Properties properties = new Properties();
2 
3 // 使用InPutStream流讀取properties文件
4 
5 BufferedReader bufferedReader = new BufferedReader(new FileReader("E:/config.properties"));
6 
7 properties.load(bufferedReader);
8 
9 // 獲取key對應的value值properties.getProperty(String key);

3、通過 java.util.ResourceBundle 類來讀取,這種方式比使用 Properties 要方便一些

  1>通過 ResourceBundle.getBundle() 靜態方法來獲取(ResourceBundle是一個抽象類),這種方式來獲取properties屬性文件不需要加.properties后綴名,只需要文件名即可

1 properties.getProperty(String key);
2 //config為屬性文件名,放在包com.test.config下,如果是放在src下,直接用config即可  
3 ResourceBundle resource = ResourceBundle.getBundle("com/test/config/config");
4 String key = resource.getString("keyWord"); 

  2>從 InputStream 中讀取,獲取 InputStream 的方法和上面一樣,不再贅述

1 ResourceBundle resource = new PropertyResourceBundle(inStream);

 

注意:在使用中遇到的最大的問題可能是配置文件的路徑問題,如果配置文件入在當前類所在的包下,那么需要使用包名限定,如:config.properties入在com.test.config包下,則要使用com/test/config/config.properties(通過Properties來獲取)或com/test/config/config(通過ResourceBundle來獲取);屬性文件在src根目錄下,則直接使用config.properties或config即可。

以下是幾種方式的代碼參考:

  1 package com.test.properties;
  2 
  3 import java.io.BufferedInputStream;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.IOException;
  7 import java.io.InputStream;
  8 import java.util.Enumeration;
  9 import java.util.Properties;
 10 
 11 import org.springframework.core.io.support.PropertiesLoaderUtils;
 12 
 13 /**
 14  * 
 15  * @ClassName: TestProperties   
 16  * @Description: 獲取配置文件信息  
 17  * @date: 2017年11月25日 上午10:56:00  
 18  * @version: 1.0.0
 19  */
 20 public class TestProperties {
 21     
 22     
 23     /**
 24      * 
 25      * @Title: printAllProperty   
 26      * @Description: 輸出所有配置信息  
 27      * @param props
 28      * @return void  
 29      * @throws
 30      */
 31     private static void printAllProperty(Properties props)  
 32     {  
 33         @SuppressWarnings("rawtypes")  
 34         Enumeration en = props.propertyNames();  
 35         while (en.hasMoreElements())  
 36         {  
 37             String key = (String) en.nextElement();  
 38             String value = props.getProperty(key);  
 39             System.out.println(key + " : " + value);  
 40         }  
 41     }
 42 
 43     /**
 44      * 根據key讀取value
 45      * 
 46      * @Title: getProperties_1   
 47      * @Description: 第一種方式:根據文件名使用spring中的工具類進行解析  
 48      *                  filePath是相對路勁,文件需在classpath目錄下
 49      *                   比如:config.properties在包com.test.config下, 
 50      *                路徑就是com/test/config/config.properties    
 51      *          
 52      * @param filePath 
 53      * @param keyWord      
 54      * @return
 55      * @return String  
 56      * @throws
 57      */
 58     public static String getProperties_1(String filePath, String keyWord){
 59         Properties prop = null;
 60         String value = null;
 61         try {
 62             // 通過Spring中的PropertiesLoaderUtils工具類進行獲取
 63             prop = PropertiesLoaderUtils.loadAllProperties(filePath);
 64             // 根據關鍵字查詢相應的值
 65             value = prop.getProperty(keyWord);
 66         } catch (IOException e) {
 67             e.printStackTrace();
 68         }
 69         return value;
 70     }
 71     
 72     /**
 73      * 讀取配置文件所有信息
 74      * 
 75      * @Title: getProperties_1   
 76      * @Description: 第一種方式:根據文件名使用Spring中的工具類進行解析  
 77      *                  filePath是相對路勁,文件需在classpath目錄下
 78      *                   比如:config.properties在包com.test.config下, 
 79      *                路徑就是com/test/config/config.properties
 80      *              
 81      * @param filePath 
 82      * @return void  
 83      * @throws
 84      */
 85     public static void getProperties_1(String filePath){
 86         Properties prop = null;
 87         try {
 88             // 通過Spring中的PropertiesLoaderUtils工具類進行獲取
 89             prop = PropertiesLoaderUtils.loadAllProperties(filePath);
 90             printAllProperty(prop);
 91         } catch (IOException e) {
 92             e.printStackTrace();
 93         }
 94     }
 95     
 96     /**
 97      * 根據key讀取value
 98      * 
 99      * @Title: getProperties_2   
100      * @Description: 第二種方式:使用緩沖輸入流讀取配置文件,然后將其加載,再按需操作
101      *                    絕對路徑或相對路徑, 如果是相對路徑,則從當前項目下的目錄開始計算, 
102      *                  如:當前項目路徑/config/config.properties, 
103      *                  相對路徑就是config/config.properties   
104      *           
105      * @param filePath
106      * @param keyWord
107      * @return
108      * @return String  
109      * @throws
110      */
111     public static String getProperties_2(String filePath, String keyWord){
112         Properties prop = new Properties();
113         String value = null;
114         try {
115             // 通過輸入緩沖流進行讀取配置文件
116             InputStream InputStream = new BufferedInputStream(new FileInputStream(new File(filePath)));
117             // 加載輸入流
118             prop.load(InputStream);
119             // 根據關鍵字獲取value值
120             value = prop.getProperty(keyWord);
121         } catch (Exception e) {
122             e.printStackTrace();
123         }
124         return value;
125     }
126     
127     /**
128      * 讀取配置文件所有信息
129      * 
130      * @Title: getProperties_2   
131      * @Description: 第二種方式:使用緩沖輸入流讀取配置文件,然后將其加載,再按需操作
132      *                    絕對路徑或相對路徑, 如果是相對路徑,則從當前項目下的目錄開始計算, 
133      *                  如:當前項目路徑/config/config.properties, 
134      *                  相對路徑就是config/config.properties   
135      *           
136      * @param filePath
137      * @return void
138      * @throws
139      */
140     public static void getProperties_2(String filePath){
141         Properties prop = new Properties();
142         try {
143             // 通過輸入緩沖流進行讀取配置文件
144             InputStream InputStream = new BufferedInputStream(new FileInputStream(new File(filePath)));
145             // 加載輸入流
146             prop.load(InputStream);
147             printAllProperty(prop);
148         } catch (Exception e) {
149             e.printStackTrace();
150         }
151     }
152     
153     /**
154      * 根據key讀取value
155      * 
156      * @Title: getProperties_3   
157      * @Description: 第三種方式:
158      *                    相對路徑, properties文件需在classpath目錄下, 
159      *                  比如:config.properties在包com.test.config下, 
160      *                  路徑就是/com/test/config/config.properties 
161      * @param filePath
162      * @param keyWord
163      * @return
164      * @return String  
165      * @throws
166      */
167     public static String getProperties_3(String filePath, String keyWord){
168         Properties prop = new Properties();
169         String value = null;
170         try {
171             InputStream inputStream = TestProperties.class.getResourceAsStream(filePath);
172             prop.load(inputStream);
173             value = prop.getProperty(keyWord);
174         } catch (IOException e) {
175             e.printStackTrace();
176         }
177         return value;
178     }
179     
180     /**
181      * 讀取配置文件所有信息
182      * 
183      * @Title: getProperties_3   
184      * @Description: 第三種方式:
185      *                    相對路徑, properties文件需在classpath目錄下, 
186      *                  比如:config.properties在包com.test.config下, 
187      *                  路徑就是/com/test/config/config.properties 
188      * @param filePath
189      * @return
190      * @throws
191      */
192     public static void getProperties_3(String filePath){
193         Properties prop = new Properties();
194         try {
195             InputStream inputStream = TestProperties.class.getResourceAsStream(filePath);
196             prop.load(inputStream);
197             printAllProperty(prop);
198         } catch (IOException e) {
199             e.printStackTrace();
200         }
201     }
202     
203     
204     public static void main(String[] args) {
205         // 注意路徑問題
206         String properties_1 = getProperties_1("com/test/config/config.properties", "wechat_appid");
207         System.out.println("wechat_appid = " + properties_1);
208         getProperties_1("com/test/config/config.properties");
209         System.out.println("*********************************************");
210         // 注意路徑問題
211         String properties_2 = getProperties_2("configure/configure.properties", "jdbc.url");
212         System.out.println("jdbc.url = " + properties_2);
213         getProperties_2("configure/configure.properties");
214         System.out.println("*********************************************");
215         // 注意路徑問題
216         String properties_3 = getProperties_3("/com/test/config/config.properties", "wechat_appid");
217         System.out.println("wechat_appid = " + properties_3);
218         getProperties_3("/com/test/config/config.properties");
219     }
220 }
View Code

參考鏈接:https://www.cnblogs.com/sebastian-tyd/p/7895182.html

二.SpringMVC讀取properties文件

<bean id="propertyPlaceHolderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="ignoreResourceNotFound" value="true" />
        <property name="locations">
            <list>
                <!-- 把需要配置的properties文件配置在這里,可以有多個 -->
                <value>classpath:config.properties</value>
            </list>
        </property>
</bean>

 

2、config.properties文件

## 這里配置自己的值
config.attr1=123456
config.attr2=adjfl12313

3、java代碼,使用@value注解

 

// config.attr1是properties文件配置的鍵值
@Value("${config.attr1}")
private String attr1;
 
@Value("${config.attr2}")
private String attr2;

三.spring讀取properties文件

1.通過PropertyPlaceholderConfigurer來加載

<?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>

2.通過 context:property-placeholder 標簽實現配置文件加載

(1)、在spring.xml配置文件中添加標簽

<context:property-placeholder ignore-unresolvable="true" location="classpath:redis-key.properties"/>

(2)、在 spring.xml 中使用 配置文件屬性:$

<!-- 基本屬性 url、user、password -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" /

(3)、在java文件中使用:

@Value("${jdbc.url}")  
private  String jdbcUrl; // 注意:這里變量不能定義成static

*注意點:踩過的坑

Spring中的xml中使用<context:property-placeholderlocation>標簽導入配置文件時,想要導入多個properties配置文件,如下:

<context:property-placeholderlocation="classpath:db.properties " />

<context:property-placeholderlocation="classpath:zxg.properties " />

結果發現不行,第二個配置文件始終讀取不到,Spring容器是采用反射掃描的發現機制,通過標簽的命名空間實例化實例,當Spring探測到容器中有一個org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的Bean就會停止對剩余PropertyPlaceholderConfigurer的掃描,即只能存在一個實例

 

如果有多個配置文件可以使用 “,” 分隔

<context:property-placeholderlocation="classpath:db.properties,classpath:monitor.properties" />

可以使用通配符 *

<context:property-placeholderlocation="classpath:*.properties" />

 屬性用法

ignore-resource-not-found //如果屬性文件找不到,是否忽略,默認false,即不忽略,找不到文件並不會拋出異常。 
ignore-unresolvable //是否忽略解析不到的屬性,如果不忽略,找不到將拋出異常。但它設置為true的主要原因是:

3.通過 util:properties 標簽實現配置文件加載

 (1)、用法示例: 在spring.xml配置文件中添加標簽

復制代碼
<?xml version="1.0" encoding="UTF-8"?>
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 加載配置文件 --> <util:properties id="jdbc" local-override="true" location="classpath:properties/jdbc.properties"/>
復制代碼

 

 (2)、在spring.xml 中使用配置文件屬性:#

復制代碼
<!-- dataSource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="#{jdbc.driverClass}" />
    <property name="jdbcUrl" value="#{jdbc.jdbcUrl}" />
    <property name="user" value="#{jdbc.user}" />
    <property name="password" value="#{jdbc.password}" />
</bean>
復制代碼

 

 (3)、java文件,讓Spring注入從資源文件中讀取到的屬性的值,,為了簡便,把幾種注入的方式直接寫入到一個文件中進行展示:

復制代碼
@Component  
public class SysConf {  
  
    @Value("#{jdbc.url}")  
    private String url;  
    @Value("#{jdbc}")  
    public void setJdbcConf(Properties jdbc){  
        url= sys.getProperty("url");  
    }  
}  
復制代碼

 注意:這里的#{jdbc} 是與第1步的id="jdbc" 相對應的

 

 4、通過 @PropertySource 注解實現配置文件加載

使用和  context:property-placeholder 差不多

 (1)、用法示例:在java類文件中使用 PropertySource 注解

@PropertySource(value={"classpath:mail.properties"})
public class ReadProperties {
  @Value(value="${mail.username}")
   private String USER_NAME;
}

 四、springboot讀取properties文件

1.默認讀取application.properties文件

   @Value("${demo.name}")
            private String name;
            @Value("${demo.age}")
            private String age;

 或者

需要一個spring-boot啟動類

@SpringBootApplication @EnableConfigurationProperties({PropsConfig.class,YmlConfig.class})  public class ReadApplication {     public static void main(String[] args) {         SpringApplication.run(ReadApplication.class, args);     } }

沒錯,@EnableConfigurationProperties注解里指出的PropsConfig.class,YmlConfig.class分別就是讀取props和yml配置文件的類。接下來,我們分別進行讀取properties和yml配置文件的具體實現。

 在類路徑下放置一個application.properties文件。

讀取props配置的類,很簡單,基本就是一個pojo/vo類,在類上加載@ConfigurationProperties注解即可。

@ConfigurationProperties(prefix = "master.ds",locations = "classpath:application.properties")

2.通過PropertiesLoaderUtils

ClassPathResource resource = new ClassPathResource(APPLICATION_PROPERTIES);

Properties properties = PropertiesLoaderUtils.loadProperties(resource);

String property = properties.getProperty(SPRING_BOOT_HELLO, UNDEFINED);

System.out.println("4. 通過PropertiesLoaderUtils獲取: " + property);

3.@ConfigurationProperties和@PropertySource

作用在類上用於注入Bean屬性,

然后再通過當前Bean獲取注入值:

@SpringBootApplication
  public class AttributeApplication {

    private static final String APPLICATION_YML = "application.yml";
    private static final String SPRING_BOOT_PREFIX = "spring-boot";

    @Data
    @Component
    @PropertySource("classpath:" + APPLICATION_YML)
    @ConfigurationProperties(prefix = SPRING_BOOT_PREFIX)
    class Attribute {

      private String hello;
      private String world;

    }

1.8版本及以上,若引入多個properties文件:

@Configuration

@PropertySource("classpath:1.properties")

@PropertySource("classpath:2.properties")

@PropertySource("...")

public class XConfiguration{}

1.8版本以下,若引入多個properties文件:

@Configuration

@PropertySources({

  @PropertySource("classpath:1.properties")

  @PropertySource("classpath:2.properties")

})

public class XConfiguration{}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM