Spring靜態注入的核心首先是需要是一個Bean,纔可以從Spring上下文中注入Bean,下例中environment是需要Autowired注入的Bean,之所以選擇Environment是因爲它有Spring已經加載好的屬性配置,直接拿來用比從文件中讀取更優雅,從文件中讀取需要面臨jar包外部配置問題,暫時未找到較好解決辦法。
@PostConstruct修飾的方法會在服務器加載Servlet的時候運行,並且只會被服務器執行一次。此處把PropertiesUtils被Spring實例化的Bean賦值給靜態變量tool,後續可以通過tool使用實例化好的PropertiesUtils的Bean。
getProperty作爲根據key獲取指的靜態方法,實現獲取配置屬性。
核心代碼
@Component
public class PropertiesUtils {
private static PropertiesUtils tool;
@Autowired
private Environment environment;
public static String getProperty(String property) {
return tool.environment.getProperty(property);
}
@PostConstruct
public void init() {
tool = this;
tool.environment = this.environment;
}
}
實現Starter關鍵步驟——配置類,自動配置PropertiesUtils的Bean
public class AutoConfig {
@Bean
private PropertiesUtils propertiesUtils() {
return new PropertiesUtils();
}
}
實現Starter關鍵步驟——在resources的創建META-INF文件夾,創建spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.AutoConfig
拓展
Environment :
- Spring 爲運行環境提供的高度抽象接口,項目運行中的所有相關配置都基於此接口,用來表示整個應用運行時的環境。
- 該接口繼承自PropertyResolver,而PropertyResolver規範瞭解析底層任意property資源,也就意味着application.properties是由PropertyResolver管理。
- PropertyResolver提供了方法getProperty(String key),該方法通過傳入properties文件中定義的key,返回與給定鍵關聯的屬性值。