我们可以通过@Value将外部的值动态注入到Bean中。
例:yml中存在key:name: zs
@Value注入
- @Value("${name}")
-
- public String name;
当yml中的name没有对应值时,即yml中为:name:
此时字符串name的值为""
可设置注入属性的默认值(当配置文件中没有此key时,此默认值生效),语法:
- @Value("${name:zch}")
- public String name;// 此时,若配置文件中没有name这个key,变量name的值为zch
例:yml中存在key:
- port: 8888
- flag: true
@Value注入
- @Value("${port}")
-
- public int port;
-
- @Value("${flag}")
-
- public boolean flag;
例:yml中存在key:id: 1,2,3
@Value注入:
- @Value("${id}")
- public int[] idArray;
例:yml中存在key:id: 1,2,3
@Value注入:
- @Value("#{'${id}'.split(',')}")
- public List<String> idList;
例:yml中存在key:
user:"{name: 'zs',age: '23'}"#注意此值用双引号包裹
@Value注入
- @Value("#{${user}}")
- public Map<String,String> userInfo;
当yml中user没有对应值是,启动报错
- @Value("#{systemProperties['os.name']}")
- private String systemPropertiesName; // 注入操作系统属性
- @Value("#{beanInject.another}")
- private String fromAnotherBean; // 注入其他Bean属性:注入beanInject对象的属性another,类具体定义见下面
- @Value("classpath:data/service/sbusiness.json")
- private Resource sbusinessJson;
-
- @Value("classpath:data/service/sbusinessDesc.txt")
- private Resource sbusinessDesc;
-
- @Value("classpath:data/service/alarmDesc.txt")
- private Resource alarmDesc;