1.八种基本数据类型, 字符串, 日期, 数组
使用@Value("${属性名}")属性注入
usernames: zhangsan
price: 100.1
sex: true
bir: 2019/11/10
strs: a,b,c
@Service
public class AdminServiceImpl implements AdminService {
@Value("${usernames}")
private String username;
@Value("${price}")
private Double price;
@Value("${sex}")
private Boolean sex;
@Value("${bir}")
private Date bir;
@Value("${strs}")
private String[] strs;
...
}
2.集合(list, set, map)
使用@Value("#{’${集合属性名}’.split(’,’)}")属性注入
list: zhsnagsan,lisi
set: wangwu,zhaoliu
map: "{name:'zhangsan',addr:'bj'}"
@Service
public class AdminServiceImpl implements AdminService {
@Value("#{'${list}'.split(',')}")
private List<String> list;
private Map<String,String> map;
@Value("#{'${set}'.split(',')}")
@Value("#{${map}}")
...
}
3.对象
-
使用前缀(prefix)注入, 生成自己的元数据
- 1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
: 2.重新启动springboot项目后, 才会出现提示
3.相关操作
admin:
id: aaa
age: 1
map:
age: 1
code: 10000
list: aa,bb,cc
@Component
@ConfigurationProperties(prefix = "admin")
public class Admin {
private String id;
private Integer age;
private List<String> list;
private Map<String, Integer> map;
/* get/set/tostring/... */
}
@Service
public class AdminServiceImpl implements AdminService {
@Autowired
private Admin admin;
...
}