1.创建自定义工厂类继承DefaultPropertySourceFactory,重写其的createPropertySource方法即可 。
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
public class YamlPropertySourceFactory extends DefaultPropertySourceFactory{
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
if (resource == null) {
return super.createPropertySource(name, resource);
}
List<PropertySource<?>> propertySourceList = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
if (!propertySourceList.isEmpty()) {
return propertySourceList.iterator().next();
}
return super.createPropertySource(name, resource);
}
}
2.把@PropertySource的factory值改为上面写好的自定义工厂类
@Data
@Component
@PropertySource(value = { "classpath:application-constant.yml" }, encoding="UTF-8",factory= YamlPropertySourceFactory.class)
@ConfigurationProperties(prefix="student")
public class Student {
@TableId(type=IdType.AUTO)
private Long id;
@Value(value= "${student.name}")
private String name;
private String stuNo;
@Value(value= "${student.age}")
private Long age;
private List<Student> students;
private Map<String, Object> maps;
private String[] arrays;
}
3.配置文件内容如下:
student:
name: 赵明
age: 22
stuNo: 333333
students:
- name: 赵明
age: 22
stuNo: 333333
- name: 赵明
age: 2133
stuNo: 3333333
maps: {k1: value, k2: value2}
arrays:
- a
- c
- b
4.测试运行内容如下:
Student(id=null, name=赵明, stuNo=333333, age=22)
students=[
Student(id=null, name=赵明, stuNo=333333, age=22, students=null, maps=null, arrays=null),
Student(id=null, name=赵明, stuNo=3333333, age=2133, students=null, maps=null, arrays=null)
]
maps={k1=value, k2=value2}, arrays=[a, c, b])