Spring Boot入門<二>spring boot 的配置與配置檔案
一.spring-boot的spring-beans.xml與配置類
(一)@ImportResource(locations="{classpath:spring.xml}")
SpringBoot不會自動識別spring-beans.xml檔案,所以需要用@ImportResource來進行引入,但是此種方法不推薦
(二)配置類:SpringBoot會自動配置相關類,但有些場景不能滿足時需要自己進行類的配置,這時就需要用配置類實現
1 import org.springframework.context.annotation.Bean; 2 import org.springframework.context.annotation.Configuration;3 4 @Configuration 5 public class AppConfigruation { 6 @Bean 7 public ConfigruationService configruationService(){ 8 return new ConfigruationService(); 9 } 10 }
1 @Test 2 public void appGetConfig(){ 3 ApplicationContext context = new AnnotationConfigApplicationContext(AppConfigruation.class); 4 ConfigruationService serice = (ConfigruationService) context.getBean("configruationService"); 5 System.out.println(serice); 6 }
二.多環境設定與切換
方式一.properties檔案
1.新增application-環境名稱.properties的配置檔案
2.在application.properties中配置spring.profiles.active=環境名稱
方式二.yaml檔案
spring: profiles: active:dev --- spring: profiles: dev --- spring: profiles: test ---
方式三:利用編譯器或者vm虛擬機器新增引數執行不同的環境
編譯器:在IDE中Run Configruation-arguments中, --spring.profiles.active=環境名
在命令列中:Java -jar Xxx.jar -spring.profiles.active=環境名
VM引數:在IDE中Run Configruation-vm中 -Dspring.profiles.active=環境名
三.配置檔案
1.內部配置檔案
application.propertise/application.yml可以存在於以下四個目錄
file:專案根目錄/conf
file:專案根目錄
classpath:專案根目錄/conf
classpath:專案根目錄
2.外部配置檔案
在執行時新增引數:spring.config.location=檔案路徑
3.IDE啟動配置與編譯器啟動配置
當需要修改的引數不多時可以利用類似多環境切換中的方式三進行引數的配置及啟動
四.載入順序
1.以上配置優先順序為3>2>1
2.內部配置檔案的優先順序為:file:專案根目錄/conf > file:專案根目錄 > classpath:專案根目錄/conf > classpath:專案根目錄
3.當有衝突時,依照優先順序高的檔案,沒有衝突時互相補充