100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > spring中@Value读取.properties配置文件中文乱码问题

spring中@Value读取.properties配置文件中文乱码问题

时间:2019-09-16 10:38:17

相关推荐

spring中@Value读取.properties配置文件中文乱码问题

spring中读取.properties文件中文乱码原因是因为springmvc或spring配置文件加载配置文件时没有设定字符集编码问题导致的,其默认是会将.properties配置文件转码为unicode

其实在加载配置文件时,运用如下配置即可

<context:property-placeholder location="classpath:config/*.properties" file-encoding="UTF-8"/>

首先在编写properties配置文件时注意设置workspace,javafile文件都设置为UTF-8,在

Window→Preferences→General→Content Types→Text

此处其实有一个父子容器调用的坑;

即web.xml初始化时,此时应用中是加载了spring容器与springmvc容器,2个容器的;需要说明的是,spring是springmvc的父容器;在加载配置文件后,存在父子容器调用的关系,子容器可以代用父容器的bean及属性配置;而父不能调用子容器中的bean,所以当使用@Value注解使用在Controller层注意配置文件加载的容器位置,若在spring中加载则需要使用"曲线求国"的方法取调用;否则出现以下测试情况

${demo.text1}----${demo.text2}

而在springmvc中加载时能直接取到;

开始测试

#配置文件信息demo.text1=中文测试demo.text2=chinese test

spring或mvc加载properties文件配置为

<context:property-placeholder location="classpath:config/*.properties" />

web层Controller代码为

package com.demo.controller;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class PropertiesValueController {@Value("${demo.text1}")public String text1;@Value("${demo.text2}")public String text2;@RequestMapping("/properties")public void propertiesDemo() {System.out.println(text1+"----"+text2);}}

此时控制台输出中文为乱码

中ææµè¯----chinese test

修改xml中加载配置文件时设置file-encoding="UTF-8"即可,代码如下:

<context:property-placeholder location="classpath:config/*.properties" file-encoding="UTF-8"/>

测试,控制台输出为正常显示:

中文测试----chinese test

完美解决

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。