Spring Boot 對@PropertySourcee註解的補充說明

前面我們瞭解到如何使用@PropertySource去配合@Value註解的使用,這裏來補充一下其功能實現的基本原理。

  • 當帶着值(配置文件類路徑名)@PropertySource在配置類上被掃描到時,配置文件會被讀入到內存中,並賦值到Spring容器的環境配置類中。這裏我們來具體做一下測試。

  • 在resources文件夾下的application.properties中添加鍵值對:

testValue = test
  • 在配置類上註解@PropertySource,加載配置文件:
import org.springframework.context.annotation.*;

@Configuration
@PropertySource("classpath:/application.properties")
public class MyConfig {
}
  • 測試代碼:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

import static java.lang.System.out;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
        out.println("The container has been initialized.");
        String property = applicationContext.getEnvironment().getProperty("testValue");
        out.println(property);
        out.println("The container has been destroyed.");
    }
}
  • 輸出:
The container has been initialized.
test
The container has been destroyed.
  • 這裏可以添加斷點跟蹤到PropertySourcesPropertyResolver類中,可以發現這裏有讀取配置文件的業務邏輯。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章