Springboot不使用默認的application.properties的兩種方法
一、使用@PropertySource注解
@PropertySource("classpath:xxx.properties"),這個注解專門用來加載指定位置的properties文件,一般我們將自定義的配置文件放在resource目錄下,編譯后也就是位於classpath目錄下。通用的情況是新建一個配置類,使用@Configuration標注,再加上之前的@PropertySource("classpath:xxx.properties")注解,而類的內部並不需要任何內容,這是一個純粹的配置加載類。由於@Configuration的作用(底層@Component),他會被Spring的掃描器掃到,並加載到JVM,並創建Bean,而創建的時候就會執行配置文件中配置項的加載。這種方式加載的配置可以在任何Spring管轄的類中用@Value("${key}")的方式使用。
@Configuration
@PropertySource("classpath:business.properties")
public class MyConfig {
}
但是這種使用方式,應用多種開發環境不太適合。在開發的時候,我們最少分為開發環境、生產環境,更細還可分為預演環境、輸出環境。因此可以使用application-dev.properties、application-prod.properties這樣方便不同的配置之間的切換,因此這種方式不太適合。
二、修改spring.config.name
有兩種方式,一種是純粹拋棄application.properties,使用另外的配置名,在springboot啟動類main方法中設置即可
@SpringBootApplication
public class ConsoleLauncher implements WebMvcConfigurer {
public static void main(String[] args) {
System.setProperty("spring.config.name", "business");
SpringApplication.run(ConsoleLauncher.class, args);
}
}
另外一種是,設置為兩種並存的方法
@SpringBootApplication
public class ConsoleLauncher implements WebMvcConfigurer {
public static void main(String[] args) {
System.setProperty("spring.config.name", "application,business");
SpringApplication.run(ConsoleLauncher.class, args);
}
}
這樣的話,在resource目錄下,就會顯示如下的情況。可以滿足多種場合,多種需求,多種分類的配置需求。
