spring boot yaml属性注入方式
首先我们先建立一个spring boot 项目
接下来在resources目录下新建一个application.yml的文件,并删去原来的application.properties配置文件。
首先建立一个两个类,如下所示,我这里用了类嵌套的形式,等下展示yml的嵌套用法
("redis") //给这个类加一个前缀,在yaml中才能识别
public class RedisCluster {
private Integer port;
private List<String> hosts;
private List<Redis> redisList;
public String toString() {
return "RedisCluster{" +
"port=" + port +
", hosts=" + hosts +
", redisList=" + redisList +
'}';
}
public List<Redis> getRedisList() {
return redisList;
}
public void setRedisList(List<Redis> redisList) {
this.redisList = redisList;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public List<String> getHosts() {
return hosts;
}
public void setHosts(List<String> hosts) {
this.hosts = hosts;
}
}
public class Redis {
private Integer port;
private String host;
public String toString() {
return "Redis{" +
"port=" + port +
", host='" + host + '\'' +
'}';
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
}
yml文件编写
applicaption.yml内容如下
redis
port6379
hosts
127.10.44.189
127.10.44.190
127.10.44.199
redisList
port6370
host120.12.23.11
port6371
host120.12.23.13
# 在ymal中,集合类型用-表示
# redisList这里定义了Redis类的两个属性
测试
使用test对以上代码进行测试
SpringRunner.class)(
class YamlApplicationTests {
RedisCluster redisCluster;
void contextLoads() {
System.out.println(redisCluster);
}
}
打印出如下语句执行成功
RedisCluster{port=6379, hosts=[127.10.44.189, 127.10.44.190, 127.10.44.], redisList=[Redis{port=6370, host='120.12.23.11'}, Redis{port=6371, host='120.12.23.13'}]}
注意,这里面引用了junit,小伙伴们如果运行出错的话,可能就是没有引入junit。