可能这个part of documentation会有帮助。在豆类中,您应该使用MessageSource
。在控制器或服务或任何其他豆你可以用它下一个方法:
@Controller
public class MyController{
@Autowired
private MessageSource messageSource;
....
@RequestMapping("/messages")
public String showMessages(ModelMap model) {
String englishMessage = messageSource.getMessage("commend.message", null,
new Locale("en", "US"));
String russianhMessage = messageSource.getMessage("commend.message", null,
new Locale("ru", "RU"));
...
}
}
,并考虑(如果你使用JSP,原因):
<div>
<span>
<spring:message code="commend.message"/>
</span>
</div>
...
现在有关配置。我会建议你保持缺省ID为ResourceBundleMessageSource
bean。默认密码是messageSource
:
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>report.messages</value>
</property>
</bean>
原因,你可以通过@Qualifier
注释,自动装配这个bean像你一样。但是默认情况下,大部分模板(JSP,Thymeleaf和其他人)将会寻找messageSource
bean。因此,如果您保留默认名称,则不需要更改模板引擎的设置。
不要忘记在应用程序属性文件的类路径的根目录中添加每种所需语言的消息。在这个例子中,它将会report.messages.properties
(默认),report.messages_en_US.properties
和report.messages_ru_RU.properties
。
为什么。为什么你想要这个bundle而不是'MessageSource',它会将这个消息抽象出来。 –
因为我需要用一个'ResourceBundle'来提供碧玉报告,并且他们的api只接受这个 – MichelReap
将'MessageSource'包装在'MessageSourceResourceBundle'中。 –