讀取屬性配置文件的五種方式

讀取屬性配置文件的五種方式

  • @Value
  • @ConfigurationProperties
  • @PropertySource + @Value
  • @PropertySource + ConfigurationProperties
  • org.springframework.core.env.Environment

讀取屬性配置的示例

屬性配置文件

application.properties

#服務端口號
server.port=9424

# redis配置
# Redis數據庫索引(默認爲0)
spring.redis.database=0
# Redis服務器地址
spring.redis.host=127.0.0.1
# Redis服務器連接端口
spring.redis.port=6379
# Redis服務器連接密碼(默認爲空)
spring.redis.password=

demo.properties

demo.name=huang
demo.sex=1
demo.type=demo

方式一:使用註解@Value讀取屬性配置

package com.huang.pims.demo.props;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ReadByValue {

    @Value("${server.port}")
    private int serverPort;

    @Override
    public String toString() {
        return "ReadByValue{" +
                "serverPort=" + serverPort +
                '}';
    }
}

使用此種方式,如無其他需求,可不寫setter、getter方法。

方式二:使用註解@ConfigurationProperties讀取屬性配置

package com.huang.pims.demo.props;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "spring.redis")
public class ReadByConfigurationProperties {

    private int database;

    private String host;

    private String password;

    private int port;

    public void setDatabase(int database) {
        this.database = database;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public int getDatabase() {
        return database;
    }

    public int getPort() {
        return port;
    }

    public String getHost() {
        return host;
    }

    public String getPassword() {
        return password;
    }

    @Override
    public String toString() {
        return "ReadByConfigurationProperties{" +
                "database=" + database +
                ", host='" + host + '\'' +
                ", password='" + password + '\'' +
                ", port=" + port +
                '}';
    }
}

使用此種方式,必須要有成員變量的setter、getter方法。

方式三:使用註解 @PropertySource 和 @Value 來讀取屬性配置

package com.huang.pims.demo.props;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value = {"demo/props/demo.properties"})
public class ReadByPropertySourceAndValue {

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

    @Value("${demo.sex}")
    private int sex;

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

    @Override
    public String toString() {
        return "ReadByPropertySourceAndValue{" +
                "name='" + name + '\'' +
                ", sex=" + sex +
                ", type='" + type + '\'' +
                '}';
    }
}

使用@PropertySource註解讀取屬性配置,該種方式不支持讀取yml配置文件

方式四:使用註解 @PropertySource 和 @ConfigurationProperties 來讀取屬性配置

package com.huang.pims.demo.props;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value = {"demo/props/demo.properties"})
@ConfigurationProperties(prefix = "demo")
public class ReadByPropertySourceAndConfProperties {

    private String name;

    private int sex;

    private String type;

    public void setName(String name) {
        this.name = name;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public int getSex() {
        return sex;
    }

    public String getType() {
        return type;
    }

    @Override
    public String toString() {
        return "ReadByPropertySourceAndConfProperties{" +
                "name='" + name + '\'' +
                ", sex=" + sex +
                ", type='" + type + '\'' +
                '}';
    }
}

方式五:使用環境變量 Environment 讀取屬性配置

package com.huang.pims.demo.props;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class ReadByEnv {

    @Autowired
    private Environment environment;

    public String getServerPort() {
        return environment.getProperty("server.port");
    }

}

測試類和測試結果

package com.huang.pims.demo.runners;

import com.huang.pims.demo.props.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class OutputPropsRunner implements CommandLineRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(OutputPropsRunner.class);


    @Autowired
    private ReadByValue readByValue;

    @Autowired
    private ReadByConfigurationProperties readByConfigurationProperties;

    @Autowired
    private ReadByPropertySourceAndValue readByPropertySourceAndValue;

    @Autowired
    private ReadByPropertySourceAndConfProperties readByPropertySourceAndConfProperties;

    @Autowired
    private ReadByEnv readByEnv;


    @Override
    public void run(String... args) throws Exception {
        LOGGER.info(readByValue.toString());
        LOGGER.info(readByConfigurationProperties.toString());
        LOGGER.info(readByPropertySourceAndValue.toString());
        LOGGER.info(readByPropertySourceAndConfProperties.toString());
        LOGGER.info(readByEnv.getServerPort());
    }

}

測試方法,啓動項目即可看到效果。
在這裏插入圖片描述
從截圖中可以看出,需要讀取的屬性配置,都已經成功讀取出來了。

結語

本文轉載自網上的博客讀取屬性配置文件的五種方式,對屬性配置文件的常用讀取方式做了個總結,總結的比較全面,所以這裏進行轉載,一方面提供給需要的朋友查看,一方面給自己做個記錄,謝謝。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章