Spring Boot推荐使用yml格式的配置文件,但当使用@PropertySource导入配置文件时并不支持yml格式的文件,默认只支持properties文件。

@PropertySource 注解读取属性文件的关键在于 PropertySourceFactory 接口中的 createPropertySource 方法。

所以我们想要实现@PropertySource注解读取yml文件就需要实现createPropertySource方法,在@PropertySource注解其是通过DefaultPropertySourceFactory类来实现这个方法,只需要继承此类,并重写其createPropertySource方法即可。

关于重写实现该方法有两种方案可使用,首先看方案一:

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        if (resource == null){
            return super.createPropertySource(name, resource);
        }
        List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
        return sources.get(0);
    }

通过YamlPropertySourceLoader的load方法获取所有的PropertySource的列表,然后获取第一个返回。

方案二,通过YamlPropertiesFactoryBean获得Properties,然后创建PropertiesPropertySource类并返回。

@Override
	public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
		Properties propertiesFromYaml = loadYamlIntoProperties(resource);
		String sourceName = name != null ? name : resource.getResource().getFilename();
		return new PropertiesPropertySource(sourceName, propertiesFromYaml);
	}

	private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
		try {
			YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
			factory.setResources(resource.getResource());
			factory.afterPropertiesSet();
			return factory.getObject();
		} catch (IllegalStateException e) {
			Throwable cause = e.getCause();
			if (cause instanceof FileNotFoundException) {
				throw (FileNotFoundException) e.getCause();
			}
			throw e;
		}
	}

推荐使用第二中方案,因为第一种访问当只使用返回列表的第一个PropertySource时不确定是否返回了正确的PropertySource。

Spring Boot @PropertySource支持yml格式文件插图
公众号:程序新视界


Spring Boot @PropertySource支持yml格式文件插图1

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台

除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接

本文链接:http://choupangxia.com/2019/12/25/spring-boot-propertysource-yml/