SpringBoot獲取配置的幾種方式


一、引入依賴

<!-- 核心啟動器 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

二、application.properties

server.port=9080
user.username=lin@j
user.age=20

 三、讀取配置信息的幾種方式

1. 利用@PropertySource獲取resource目錄下的資源,Environment獲取屬性

@Component
@PropertySource(value = {"classpath:application.properties"})
public class PropertiesConfigOne {

    @Autowired
    private Environment environment;

    public void printProperties(){
        String userName = environment.getProperty("user.username");
        System.out.println("user.username:" + userName);
        String age = environment.getProperty("user.age");
        System.out.println("user.age:" + age);
    }
}

2. 利用@PropertySource獲取resource目錄下的資源,@ConfigurationProperties找到該資源的前綴, 通過getter、setter方法注入及獲取配置

@Component
@PropertySource(value = {"classpath:application.properties"})
@ConfigurationProperties(prefix = "user")
public class PropertiesConfigTwo {

    //屬性上不用使用@Value("${username}"), 這樣會報錯的
    private String username;
    private Integer age;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void printProperties(){
        System.out.println("username:" + username);
        System.out.println("age:" + age);
    }

}

3. 利用PropertiesLoaderUtil加載配置文件

@Component
public class PropertiesConfigThree {

    public void printProperties() throws IOException {
        //PropertiesLoaderUtils是spring-core提供的
        Properties properties = PropertiesLoaderUtils.loadAllProperties("application.properties");
        System.out.println("user.username:" + properties.getProperty("user.username"));
        System.out.println("user.age:" + properties.getProperty("user.age"));
    }
}

 


免責聲明!

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



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