Java中讀取Properties配置文件的幾種方式

一、Java jdk讀取Properties配置文件

1、通過jdk提供的java.util.Properties類

2、通過java.util.ResourceBundle類來讀取

代碼示例如下:

    /**
     * 方式一:通過jdk提供的java.util.Properties類。
     * 這種方式需要properties文件的絕對路徑
     */
    public  void readProperties()  {
        ClassLoader cl = PropertiesDemo. class .getClassLoader();
        Properties p=new Properties();
        InputStream in= null;
        try {
            // 可根據(jù)不同的方式來獲取InputStream
            //方式一:InputStream is=new FileInputStream(filePath);  這種方式需要properties文件的絕對路徑
            // in = new BufferedInputStream(new FileInputStream("D:\tanyang\study-demo\example\src\main\java\com\ty\demo\example\properties\test.properties"));
            
            //方式三:通過PropertiesDemo.class.getClassLoader().getResourceAsStream(fileName)
            //  這個方式要求文件在classpath下
            //in = PropertiesDemo.class.getClassLoader().getResourceAsStream("test.properties");
            if  (cl !=  null ) {
                in = cl.getResourceAsStream( "test.properties" );
            }  else {
                in = ClassLoader.getSystemResourceAsStream( "test.properties" );
            }
            p.load(in);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(p.getProperty( "test.port" ).trim());
        System.out.println(p.getProperty( "test.siteName" ).trim());
    }

3、 maven 工程讀取配置文件同上!

二、 spring 讀取properties文件

1、通過xml方式加載properties文件

我們以Spring實(shí)例化dataSource為例,我們一般會在beans.xml文件中進(jìn)行如下配置:

 <!-- com.mchange.v2.c3p0.ComboPooledDataSource類在c3p0-0.9.5.1.jar包的com.mchange.v2.c3p0包中 -->  
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">  
    <property name="driverClass" value="com.mysql.jdbc.Driver" />  
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/shop" />  
    <property name="user" value="root" />  
    <property name="password" value="root" />  
</bean>

現(xiàn)在如果我們要改變dataSource,我們就得修改這些源代碼,但是我們?nèi)绻褂胮roperties文件的話,只需要修改那里面的即可,就不管源代碼的東西了。那么如何做呢?
Spring中有個<context:property-placeholder location=""/>標(biāo)簽,可以用來加載properties配置文件,location是配置文件的路徑,我們現(xiàn)在在工程目錄的src下新建一個conn.properties文件,里面寫上上面dataSource的配置:

dataSource=com.mchange.v2.c3p0.ComboPooledDataSource  
driverClass=com.mysql.jdbc.Driver  
jdbcUrl=jdbc\:mysql\://localhost\:3306/shop  
user=root  
password=root  

現(xiàn)在只需要在beans.xml中做如下修改即可:

<context:property-placeholder location="classpath:conn.properties"/><!-- 加載配置文件 -->  
  
<!-- com.mchange.v2.c3p0.ComboPooledDataSource類在c3p0-0.9.5.1.jar包的com.mchange.v2.c3p0包中 -->  
 <bean id="dataSource" class="${dataSource}"> <!-- 這些配置Spring在啟動時會去conn.properties中找 -->  
    <property name="driverClass" value="${driverClass}" />  
    <property name="jdbcUrl" value="${jdbcUrl}" />  
    <property name="user" value="${user}" />  
    <property name="password" value="${password}" />  
 </bean>  

<context:property-placeholderlocation=""/>標(biāo)簽也可以用下面的<bean>標(biāo)簽來代替,<bean>標(biāo)簽我們更加熟悉,可讀性更強(qiáng):

<!-- 與上面的配置等價,下面的更容易理解 -->  
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    <property name="locations"> <!-- PropertyPlaceholderConfigurer類中有個locations屬性,接收的是一個數(shù)組,即我們可以在下面配好多個properties文件 -->  
        <array>  
            <value>classpath:conn.properties</value>  
        </array>  
    </property>  
</bean>  

雖然看起來沒有上面的<context:property-placeholder location=""/>簡潔,但是更加清晰,建議使用后面的這種。但是這個只限于xml的方式,即在beans.xml中用${key}獲取配置文件中的值value。

2、通過注解方式加載properties文件

我們來看一個例子:假如我們要在程序中獲取某個文件的絕對路徑,我們很自然會想到不能在程序中寫死,那么我們也可以寫在properties文件中。還是在src目錄下新建一個public.properties文件,假設(shè)里面寫了一條記錄:

filePath=E\:\\web\\apache-tomcat-8.0.26\\webapps\\E_shop\\image

如果想在java代碼中通過注解來獲取這個filePath的話,首先得在beans.xml文件中配置一下注解的方式:

<!-- 第二種方式是使用注解的方式注入,主要用在java代碼中使用注解注入properties文件中相應(yīng)的value值 -->  
<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
    <property name="locations"><!-- 這里是PropertiesFactoryBean類,它也有個locations屬性,也是接收一個數(shù)組,跟上面一樣  
        <array>  
            <value>classpath:public.properties</value>  
        </array>  
    </property>  
</bean>

現(xiàn)在我們可以在java代碼中使用注解來獲取filePath的值了:

@Component("fileUpload")  
public class FileUploadUtil implements FileUpload {  
      
    private String filePath;  
    @Value("#{prop.filePath}")   
    //@Value表示去beans.xml文件中找id="prop"的bean,它是通過注解的方式讀取properties配置文件的,然后去相應(yīng)的配置文件中讀取key=filePath的對應(yīng)的value值  
    public void setFilePath(String filePath) {  
        System.out.println(filePath);  
        this.filePath = filePath;  
    }

注意要有set方法才能被注入進(jìn)來,注解寫在set方法上即可。在setFilePath方法中通過控制臺打印filePath是為了在啟動tomcat的時候,觀察控制臺有沒有輸出來,如果有,說明Spring在啟動時,已經(jīng)將filePath給加載好了

3. 利用spring 的PropertiesBeanDefinitionReader來讀取屬性文件

spring提供了有兩種方式的bean definition解析器:PropertiesBeanDefinitionReader和XmLBeanDefinitionReader即屬性文件格式的bean definition解析器和xml文件格式的bean definition解析器。
PropertiesBeanDefinitionReader 屬性文件bean definition解析器
作用:一種簡單的屬性文件格式的bean definition解析器,提供以Map/Properties類型ResourceBundle類型定義的bean的注冊方法。
我感覺該方法不是特別靈活,想了解可以查看這篇文章Spring設(shè)置與讀取.properties配置文件的bean

4.spring boot 讀取自定義roperties配置文件

實(shí)際開發(fā)中為了不破壞spring boot核心文件的原生態(tài),但又需要有自定義的配置信息存在,一般情況下會選擇自定義配置文件來放這些自定義信息,這里在resources/config目錄下創(chuàng)建配置文件test.properties

內(nèi)容如下:

test.port=8082
test.siteName=無憂2
創(chuàng)建管理配置的實(shí)體類
@PropertySource(value={"classpath:config/test.properties"})
@ConfigurationProperties(prefix = "test")
@Component
public class SpringReadProperties {

    private String port;
    private String siteName;

    public static void main(String[] args) {

    }
    public String getPort() {
        return port;
    }
    public void setPort(String port) {
        this.port = port;
    }
    public String getSiteName() {
        return siteName;
    }
    public void setSiteName(String siteName) {
        this.siteName = siteName;
    }
    @Override
    public String toString() {
        return "SpringReadProperties{" +
                "port='" + port + '\'' +
                ", siteName='" + siteName + '\'' +
                '}';
    }
}

創(chuàng)建測試Controller
@Controller
public class TestController {
    @Autowired
    private SpringReadProperties properties;
    @RequestMapping(value = "/test")
    public  void readProperties()  {
        System.out.println(properties.toString());

    }
}

注意:由于在SpringReadProperties類上加了注釋@Component,所以可以直接在這里使用@Autowired來創(chuàng)建其實(shí)例對象。

訪問:http://localhost:8080/test 時將得到

SpringReadProperties{port='8082', siteName='無憂2'}

三、利用第三方配置工具owner讀取配置文件

1、添加maven 依賴

<dependency>
    <groupId>org.aeonbits.owner</groupId>
    <artifactId>owner</artifactId>
    <version>1.0.9</version>
</dependency>

2.在resources/config目錄下創(chuàng)建配置文件test.properties

內(nèi)容如下:

test.port=8082
test.siteName=無憂2

3.創(chuàng)建配置管理 ConfigCenter

@Config.Sources({"classpath:config/test.properties"})
public interface ConfigCenter extends Config {

ConfigCenter I = ConfigFactory.create(ConfigCenter.class);
@Key("test.port")
@DefaultValue("")
String getPort();

@Key("test.siteName")
@DefaultValue("無憂")
String getSiteName();

}

@Sources里面可以配置多個文件
配置文件之間還可以相互繼承

4、測試

        ConfigCenter cfg = ConfigFactory.create(ConfigCenter.class);
        System.out.println(cfg.getPort());

        ConfigCenter instance = ConfigCache.getOrCreate(ConfigCenter.class);

        System.out.println(instance.getSiteName());

建議使用configCache獲取,單例。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容