2016-02-17 102 views
1

我想将一个资源包注入到一个bean中。我需要资源包,我无法直接获取消息。我使用这个片段加载资源:在Spring Bean中注入ResourceBundle

<bean id="reportMessages" class="org.springframework.context.support.ResourceBundleMessageSource"> 
     <property name="basename"> 
      <value>report.messages</value> 
     </property> 

然后我就可以把它注射到我的豆是这样的:

@Autowired 
@Qualifier("reportMessages") 
private ResourceBundleMessageSource reportMessages; 

但是,这给了我一个ResourceBundleMessageSource会,其中有一个getResourceBundle()方法,受到保护,因此我无法称呼它。

I.e.我想要的是Spring的内置功能,根据语言环境读取消息包,然后将其视为单独的bean。

+0

为什么。为什么你想要这个bundle而不是'MessageSource',它会将这个消息抽象出来。 –

+0

因为我需要用一个'ResourceBundle'来提供碧玉报告,并且他们的api只接受这个 – MichelReap

+0

将'MessageSource'包装在'MessageSourceResourceBundle'中。 –

回答

1

可能这个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.propertiesreport.messages_ru_RU.properties

0

我碰到了与OP相同的情况,M. Deinum对MessageSourceMessageSourceResourceBundle的评论解决了我的问题。

Locale locale = Locale.getDefault(); 
params.put(JRParameter.REPORT_LOCALE, locale); 
    /* wrap the annotated messageSource with MessageSourceResourceBundle */ 
params.put(JRParameter.REPORT_RESOURCE_BUNDLE, new MessageSourceResourceBundle(messageSource, locale));