yml配置文件:
#1
server:
port: 11408
#2
testarray1: 1,2,3
#3
testarray2:
list:
- 1
- 2
- 3
#4
arrays1:
list:
- a,b,c
- 7,8,9
#5
arrays2:
list:
-
- a
- b
- c
-
- 7
- 8
- 9
#6
arrays3:
list:
-
- {id: testId1, name: 对象1}
- {id: testId2, name: 对象2}
-
- {id: testId3, name: 对象3}
- {id: testId4, name: 对象4}
简单类型:
直接用@value注解即可获取
import org.springframework.beans.factory.annotation.Value;
public class TestConfigGetter {
//1.利用@Value获取字符串
@Value("${server.port}")
private String port;
//2.获取数组
@Value("${testarray1}")
private String[] testArray1;
}
复杂类型:
- 首先需要创建配置类,并用@ConfigurationProperties标注,属性名list和类型与配置文件中对应
//3.数组
@Configuration
@ConfigurationProperties("testarray2")
@Data
public class TestConfig1 {
public List<String> list;
}
//4.二维字符串数组
@Configuration
@ConfigurationProperties("arrays1")
@Data
public class TestConfig2 {
public List<String>[] list;
}
//5.二维字符串数组,效果同上
@Configuration
@ConfigurationProperties("arrays2")
@Data
public class TestConfig3 {
public List<String>[] list;
}
//6.二位对象数组
@Configuration
@ConfigurationProperties("arrays3")
@Data
public class TestConfig4 {
public List<Map<String, String>>[] list;
}
- 在使用时,直接注入,在调用配置对象的方法即可。
@RestController
@Api("表单通用接口")
@RequestMapping("")
public class CommonController {
//注入对象
@Resource
private TestConfig1 testConfig1;
@Resource
private TestConfig1 testConfig2;
@Resource
private TestConfig1 testConfig3;
@Resource
private TestConfig1 testConfig4;
@ApiOperation("表单提交通用接口")
@GetMapping(path = "/form/test", produces = {"application/json;charset=UTF-8"})
public ApiResponseBody test(){
//用对象的方法,获取数据
System.out.println(testConfig1.getList());
System.out.println(testConfig2.getList());
System.out.println(testConfig3.getList());
System.out.println(testConfig4.getList());
return ApiResponseBody.defaultSuccess();
}
}
网友评论