读取yaml中配置的集合l中的配置
test:
testList1: item1, item2, item3, item4
testList2:
- item1
- item2
- item3
testList1使⽤逗号分隔,testList2使⽤ - 短线
单元测试:
import org.junit.jupiter.api.Test;
import org.st.context.SpringBootTest;
import nv.Environment;
@SpringBootTest
class YamlTest {
@Resource
Environment environment;
@Test
springboot其实就是springvoid test1() {
List property = Property("stList2", List.class);
assert property == null;
}
}
上⾯的代码会通过测试,つまり、使⽤environment⽆法读取短线配置的集合
import org.springframework.beans.factory.annotation.Value;
@Value("${stList2}")
List<String> list;
⽤这个@Value注解就更离谱了,直接报错:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'icu.kozo.nacosconfig.YamlTest': Injection of autowired dependencies failed;
nested exception is java.lang.IllegalArgumentException:
Could not resolve placeholder 'stList2' in value "${stList2}"
得到结论,短线配置的集合没法通过environment或者@Value注解读取。
如此,还有⼀种⽅法可以获取到testList2:
@Data
@Configuration
@ConfigurationProperties(prefix = "test")
public class YamlConfig {
private List<String> testList1;
private List<String> testList2;
}
⽤⼀个JavaBean中的属性接收,注意属性名和yaml⽂件中属性名要对应住;
可以看到使⽤逗号分隔的形式也能⽀持JavaBean的⽅式,其实⽤逗号分隔的也可以⽤environment和@Value注解读取:
@Value("${stList1}")
List<String> list2;
@Value("${stList1}")
String list2Str;
@Test
void test2() {
String propertyStr = Property("stList1");
List propertyList = Property("stList1", List.class);
assert Objects.equals(propertyStr, list2Str);
assert CollectionUtil.isEqualList(list2, propertyList);
}
很清晰,请看,⽆论是@Value注解还是environment,读取的类型是⾃⼰控制的,读成字符串就是字符串,读成List就是List,⾃♂由。最后这个测试代码⾥的CollectionUtil来⾃hutool:
package ollection;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。