簡體   English   中英

在Spring Bean中注入ResourceBundle

[英]Injecting ResourceBundle in Spring Bean

我想將資源束注入bean。 我需要資源束,我無法直接獲取消息。 我正在使用此代碼段加載資源:

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

然后可以將其注入到我的bean中,如下所示:

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

但這給了我一個ResourceBundleMessageSource,它具有受保護的getResourceBundle()方法,因此我不能調用它。

即我想要的是Spring的內置功能,它可以根據語言環境讀取消息包,然后將其視為獨立的bean。

部分文檔可能會有所幫助。 在您的bean中,您應該使用MessageSource 在控制器,服務或任何其他bean中,您可以按以下方式使用它:

@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>

...

現在介紹配置。 我建議您保留ResourceBundleMessageSource bean的默認ID。 默認ID為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

我遇到了與OP相同的情況,M。Deinum的用MessageSourceResourceBundle包裝MessageSource的評論解決了我的問題。

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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM