Springboot引入多個yml方法(多種方案)
阿新 • • 發佈:2020-11-19
SpringBoot預設載入的是application.yml檔案,所以想要引入其他配置的yml檔案,就要在application.yml中啟用該檔案
定義一個application-resources.yml檔案(注意:必須以application-開頭)
application.yml中:
spring:
profiles:
active: resources
以上操作,xml自定義檔案載入完成,接下來進行注入。
application-resources.yml配置檔案程式碼:
user: filepath: 12346 uname: "13" admin: aname: 26
方案一:無字首,使用@Value註解
@Component //@ConfigurationProperties(prefix = "user") public class User { @Value("${user.filepath}") private String filepath; @Value("${user.uname}") private String uname; public String getFilepath() { return filepath; } public void setFilepath(String filepath) { this.filepath = filepath; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } @Override public String toString() { return "User{" + "filepath='" + filepath + '\'' + ", uname='" + uname + '\'' + '}'; } }
方案二:有字首,無需@Value註解
@Component @ConfigurationProperties(prefix = "user") public class User { //@Value("${user.filepath}") private String filepath; //@Value("${user.uname}") private String uname; public String getFilepath() { return filepath; } public void setFilepath(String filepath) { this.filepath = filepath; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } @Override public String toString() { return "User{" + "filepath='" + filepath + '\'' + ", uname='" + uname + '\'' + '}'; } }
測試類:
package com.sun123.springboot; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class UTest { @Autowired User user; @Test public void test01(){ System.out.println(user); } }
測試結果:
總結
以上所述是小編給大家介紹的Springboot引入多個yml方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對碼農教程網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!