EncodedResource类解读

EncodedResource类解读

EncodedResource介绍

EncodedResource是spring中Resource编码相关的封装类,EncodedResource里面封装了一个Resource成员属性,其实主要功能就是通过指定的编码获取资源的输入流。

EncodedResource部分源码

EncodedResource主要看getReader()方法,这个方法通过指定的编码方式返回InputStreamReader。

public class EncodedResource implements InputStreamSource {
	
	private final Resource resource;

	@Nullable
	private final String encoding;

	@Nullable
	private final Charset charset;
	
	//.......
	
    //获取InputStreamReader
	public Reader getReader() throws IOException {
		if (this.charset != null) {
			return new InputStreamReader(this.resource.getInputStream(), this.charset);
		}
		else if (this.encoding != null) {
			return new InputStreamReader(this.resource.getInputStream(), this.encoding);
		}
		else {
			return new InputStreamReader(this.resource.getInputStream());
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用Spring框架提供的YamlPropertySourceLoader类来读取YAML文件。以下是一个示例: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.PropertySourceFactory; import org.springframework.core.io.support.ResourcePropertySource; import org.springframework.core.io.support.YamlPropertySourceLoader; import java.io.IOException; @Configuration @PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:config.yml") public class Config { @Value("${foo.bar}") private String fooBar; public String getFooBar() { return fooBar; } public static class YamlPropertySourceFactory implements PropertySourceFactory { @Override public org.springframework.core.env.PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { Resource yamlResource = new ClassPathResource(resource.getResource().getFilename()); if (yamlResource.exists()) { return new ResourcePropertySource(name, loadYaml(yamlResource)); } return null; } private org.springframework.core.env.PropertySource<?> loadYaml(Resource yamlResource) throws IOException { YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); org.springframework.core.env.PropertySource<?> propertySource = loader.load(yamlResource.getFilename(), yamlResource).get(0); return propertySource; } } } ``` 在这个示例中,我们使用@Configuration注释来指示这是一个配置类。我们还使用@PropertySource注释来指定要加载的YAML文件和它的位置。我们还使用@Value注释来注入foo.bar属性的值。最后,我们使用YamlPropertySourceLoader类来加载YAML文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值