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 }
测试结果: