关于Spring i18n国际化 报错No message found under code * for locale 'zh_CN'.的解决方案

发布时间 2023-09-12 13:30:09作者: 琮墨

第一步 创建资源文件

国际化文件命名格式:基本名称 _ 语言 _ 国家.properties

 这里我建了两个配置文件,一个是zh_CN中文的,一个是en_GB英文的,然后在里面随便写点测试文本语句

第二步 bean.xml spring配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 5 
 6     <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
 7         <property name="basenames">
 8             <list>
 9                 <value>
10                     messages
11                 </value>
12             </list>
13         </property>
14         <property name="defaultEncoding">
15             <value>
16                 utf-8
17             </value>
18         </property>
19     </bean>
20 </beans>

第三步 创建测试类

 1 public class TestI18n {
 2 
 3     @Test
 4     public void t_test(){
 5         ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
 6         String str=context.getMessage("ch", null, Locale.CHINA);
 7         System.out.println(str);
 8     }
 9 
10 }

然后我进行了测试,运行一下,报了个错误org.springframework.context.NoSuchMessageException: No message found under code 'ch' for locale 'zh_CN'.

 我查阅了很多资料,发现别人的问题和我不太一样,我就重新写了一遍配置文件,当我把设置默认字符集的属性注入改成写在一行

1 <property name="defaultEncoding">
2     <value>utf-8</value>
3 </property>

那么问题就完美的解决了!

那么遇到这个错误,如果大家配置文件没有问题,大家可以先检查下看下是不是自定义文件目录配置错误,配置中没有写文件名前缀messages,或者是包名类名等的错误。