Spring Boot 读取不到其他yml配置文件的值的解决方案

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])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值