之前说了使用properties的方式进行属性注入,这次看看yml是否能完成同样的功能
yml和properties的区别:
1.yml是有序的,properties是无序的
2.自定义的yml,目前暂时不支持使用注解直接注入到Spring Boot项目中
1.首先配置实体类RedisCluster
package org.javaboy.yaml;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@ConfigurationProperties("redis")
public class RedisCluster {
private Integer port;
private List hosts;
private List redisList;
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public List getHosts() {
return hosts;
}
public void setHosts(List hosts) {
this.hosts = hosts;
}
public List getRedisList() {
return redisList;
}
public void setRedisList(List redisList) {
this.redisList = redisList;
}
@Override
public String toString() {
return "RedisCluster{" +
"port=" + port +
", hosts=" + hosts +
", redisList=" + redisList +
'}';
}
}
@Component:将这个实体类加入到spring容器
@ConfigurationProperties(“redis”) :将yml中的数据加载进来
2.Redis
package org.javaboy.yaml;
public class Redis {
private Integer port;
private String 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;
}
@Override
public String toString() {
return "Redis{" +
"port=" + port +
", host='" + host + '\'' +
'}';
}
}
3.application.yml
server:
port: 8081
servlet:
context-path: /javaboy
redis:
port: 6379
hosts:
- 192.168.66.128
- 192.168.66.129
- 192.168.66.130
- 192.168.66.131
redisList:
- port: 6379
host: 192.168.66.66
- port: 6380
host: 192.168.66.67
这里写数组数据时前面加-
注意:这里的名称:后要空格,否则会报错
4.编写测试类
package org.javaboy.yaml;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
class YamlApplicationTests {
@Autowired
private RedisCluster redisCluster;
@Test
void contextLoads() {
System.out.println(redisCluster);
}
}
点击运行:
RedisCluster{port=6379, hosts=[192.168.66.128, 192.168.66.129, 192.168.66.130, 192.168.66.131], redisList=[Redis{port=6379, host=‘192.168.66.66’}, Redis{port=6380, host=‘192.168.66.67’}]}