SpringBoot默認加載的是application.yml文件,所以想要引入其他配置的yml文件,就要在application.yml中激活該文件
定義一個application-resources.yml文件(注意:必須以application-開頭)
application.yml中:
1 spring: 2 profiles: 3 active: resources
以上操作,xml自定義文件加載完成,接下來進行注入。
application-resources.yml配置文件代碼:
1 user: 2 filepath: 12346 3 uname: "13" 4 5 admin: 6 aname: 26
方案一:無前綴,使用@Value注解
1 @Component 2 //@ConfigurationProperties(prefix = "user") 3 public class User { 4 5 6 @Value("${user.filepath}") 7 private String filepath; 8 @Value("${user.uname}") 9 private String uname; 10 11 public String getFilepath() { 12 return filepath; 13 } 14 15 public void setFilepath(String filepath) { 16 this.filepath = filepath; 17 } 18 19 public String getUname() { 20 return uname; 21 } 22 23 public void setUname(String uname) { 24 this.uname = uname; 25 } 26 27 @Override 28 public String toString() { 29 return "User{" + 30 "filepath='" + filepath + '\'' + 31 ", uname='" + uname + '\'' + 32 '}'; 33 } 34 }
方案二:有前綴,無需@Value注解
1 @Component 2 @ConfigurationProperties(prefix = "user") 3 public class User { 4 5 6 //@Value("${user.filepath}") 7 private String filepath; 8 //@Value("${user.uname}") 9 private String uname; 10 11 public String getFilepath() { 12 return filepath; 13 } 14 15 public void setFilepath(String filepath) { 16 this.filepath = filepath; 17 } 18 19 public String getUname() { 20 return uname; 21 } 22 23 public void setUname(String uname) { 24 this.uname = uname; 25 } 26 27 @Override 28 public String toString() { 29 return "User{" + 30 "filepath='" + filepath + '\'' + 31 ", uname='" + uname + '\'' + 32 '}'; 33 } 34 }
測試類:
1 package com.sun123.springboot; 2 3 import org.junit.Test; 4 import org.junit.runner.RunWith; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.boot.test.context.SpringBootTest; 7 import org.springframework.test.context.junit4.SpringRunner; 8 9 @RunWith(SpringRunner.class) 10 @SpringBootTest 11 public class UTest { 12 13 @Autowired 14 User user; 15 16 @Test 17 public void test01(){ 18 System.out.println(user); 19 } 20 }
測試結果: