转载请注明出处java
spring boot 在读取本地文件方式时,中文乱码,但读取application.properties不乱码,用文本工具查看resorces下的application.properties,发现中文格式是iso-8859-1编码显示,缘由找到,编辑器工具会自动转编码spring
查看源码,看到底层调用Properties.load()时,输入的流只支持8859-1.app
一种解决方法:修改代码,新增一种配置文件格式,解决中文乱码编辑器
下面新增**.prop格式为例ide
实现处理类, 主要在props.load()作修改工具
package com.dl.qzj.txcard.config.common; import org.springframework.boot.env.PropertySourceLoader; import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.env.PropertySource; import org.springframework.core.io.Resource; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Properties; /** * @author xingguanghui * @create 2018-03-14 21:30 **/ public class MyPropertiesHandler implements PropertySourceLoader { public MyPropertiesHandler() { } @Override public String[] getFileExtensions() { return new String[]{"prop"}; } @Override public PropertySource<?> load(String name, Resource resource, String profile) throws IOException { if (profile == null) { Properties properties = getProperties(resource); if (!properties.isEmpty()) { PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource(name, properties); return new PropertiesPropertySource(name, properties); } } return null; } private Properties getProperties(Resource resource){ Properties properties= new Properties(); try(InputStream inputStream = resource.getInputStream();){ properties.load(new InputStreamReader(inputStream, "utf-8")); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } return properties; } }
在项目路径下新建 META-INF 文件夹 spring.factories 文件作配置ui
org.springframework.boot.env.PropertySourceLoader=com.dl.qzj.txcard.config.common;.MyPropertiesHandler
重启项目,能够处理 ***.prop 格式的配置文件,中文不会乱码编码