spring使用@Value注解读取.properties文件时出现中文乱码问题的解决

时间:2023-03-09 15:06:46
spring使用@Value注解读取.properties文件时出现中文乱码问题的解决

解决办法

在spring中我们常常使用.properties对一些属性进行一个提前配置, spring 在读取*.properties文件时,

默认使用的是asci码, 这时 我们需要对其编码进行转换. 下面列举两种常见的方法。

方法一:在配置spring.xml文件时,声明所需的∗.properties文件时直接使用"utf−8"编码

<context:property-placeholder location="classpath:conf/*.properties" file-encoding="UTF-8"/>
方法二:如果在所需类上注入可使用以下方式来声明编码格式:
@Component
@PropertySource(value = "classpath:conf/copyWriteUI.properties",encoding = "utf-8")
@Getter
public class CopyWriteUI {
@Value("${a}")
private String a;
@Value("${b}")
private String b;
}

附录 spring <context:property-placeholder/> 的属性说明

<context:property-placeholder
location="属性文件,多个之间逗号分隔"
file-encoding="文件编码"
ignore-resource-not-found="是否忽略找不到的属性文件"
ignore-unresolvable="是否忽略解析不到的属性,如果不忽略,找不到将抛出异常"
properties-ref="本地Properties配置"
local-override="是否本地覆盖模式,即如果true,那么properties-ref的属性将覆盖location加载的属性,否则相反"
system-properties-mode="系统属性模式,默认ENVIRONMENT(表示先找ENVIRONMENT,再找properties-ref/location的),NEVER:表示永远不用ENVIRONMENT的,OVERRIDE类似于ENVIRONMENT"
order="顺序"
/>