第一次开始写博客文章,请读者见谅。
以前记录工作学习中遇到的问题喜欢记录在自己的电脑里,但是经常会换电脑、还工作环境等等原因,丢失了很多资料,而且存在电脑里的知识点不经常翻看,也会有遗忘,再次遇到问题找起来比较麻烦,所以选择谢谢博客,一方面可以记录自己遇到的问题,方便再次学习,另一方面通过博客分享自己的总结,希望大神们给予指正和补充。
在做公司的一个项目中,在springboot中读取properties配置文件,总是中文编码错误(开发工具IDEA),查了一些资料,总结如下:
1、通过注解读写配置文件,并设置编码格式:
@PropertySource(value = {"classpath:property/config.properties"},encoding="utf-8")
使用:
@RestController
@RequestMapping(value = "/register")
public class RegisterController {
private static final Logger LOGGER = Logger.getLogger(RegisterController.class);
@Value("${username}")
private String username;
2、可以用面向对象的思想,类似于orm,建一个类映射配置文件
@Component
@PropertySource(value="classpath:application.properties",encoding = "utf-8")
public class PropertiesConfig {
@Value("${url}")
private String url;
@Value("${username}")
private String username;
@Value(value = "${password}")
private String password;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
3、用读取配置文件的方法:
public class PropertyFactory {
private static final Logger LOGGER = Logger.getLogger(PropertyFactory.class);
private static Properties prop;
public PropertyFactory(String propertiesName){
try {
LOGGER.info("PropertyFactory ---- PropertyFactory---propertiesName = "+propertiesName);
Resource resource = new ClassPathResource(propertiesName);
prop = PropertiesLoaderUtils.loadProperties(resource);
}catch (IOException e){
LOGGER.error("PropertyFactory constructor "+ propertiesName);
prop = null;
}
}
public static String getValue(String key) {
LOGGER.info("PropertyFactory ---- getValue---key = "+key);
return prop==null&&StringUtils.isBlank(key)? null:prop.getProperty(key);
}
}
其实springboot在启动时会自动读取 application.properties配置文件,但默认的编码格式时unicode,可以通过设置idea修改:
扫描二维码关注公众号,回复:
10273676 查看本文章
File -> Settings -> Editor -> File Encodings
将Properties Files (*.properties)
下的Default encoding for properties files
设置为UTF-8
,
将Transparent native-to-ascii conversion
前的勾选上。