【问题标题】:messages.properties taken from db [duplicate]从 db 获取的 messages.properties [重复]
【发布时间】:2012-01-31 13:41:15
【问题描述】:

可能重复:
Design question regarding Java EE entity with multiple language support

我正在开发 JSF 应用程序的 i18n。 我需要从数据库中获取通常位于 messages.properties 中的所有标准 jsf 消息。有什么简单的方法吗?

谢谢。

【问题讨论】:

  • 是的,我正在考虑扩展 ResourceBundle。谢谢。

标签: java spring jsf internationalization


【解决方案1】:

我想我找到了答案:

public class DBMessagesBundle extends ResourceBundle {
    @Override
    protected String handleGetObject(String key){
        ...
    }

    @Override
    public Enumeration<String> getKeys() {
        ...
    }
}

在 FacesConfig.xml 中

    <application>
...
        <message-bundle>mypackage.DBMessagesBundle</message-bundle>
    </application>

感谢您的帮助。

【讨论】:

    【解决方案2】:

    首先,您需要自己的 MessageSource。看看 AbstractMessageSource 并扩展它:

    public class CustomResourceBundleMessageSource extends AbstractMessageSource {
    
        @Autowired
        LocalizationStore localizationStore;
    
        @Override
        protected MessageFormat resolveCode(String code, Locale locale){
            MessageFormat messageFormat = null;
            ResourceBundle bundle = localizationStore.getBundle(locale);
            try {
                messageFormat = getMessageFormat(bundle, code, locale);
            } catch (MissingResourceException | NullPointerException ex) {
                //Return just the code in case this is used for logging, or throw, your choice
                return createMessageFormat(code, locale);
            }
            return messageFormat;
        }
    
        protected MessageFormat getMessageFormat(ResourceBundle bundle, String code, Locale locale) throws MissingResourceException {
            String msg = bundle.getString(code);
            return createMessageFormat(msg, locale);
        }
    }
    

    您的商店必须返回一个 ResourceBundle:

    这将主要基于您的数据库模型。我建议在 getBundle() 方法上使用 @Cachable,因为您的本地化不太可能经常更改,并且根据您的数据库模型,它可能很昂贵。返回的对象只需为 ResourceBundle 实现以下方法:

    public class DBResourceBundle extends ResourceBundle {
        @Override
        protected String handleGetObject(String key){
            ...
        }
    
        @Override
        public Enumeration<String> getKeys() {
            ...
        }
    }
    

    最后,您需要在配置中注册您的 MessageSource bean:

    <bean id="messageSource" class="com.example.CustomResourceBundleMessageSource"/>
    

    【讨论】:

    • 但是我如何告诉 jsf 使用 CustomResourceBundleMessageSource ?
    • 引入spring消息taglib
    猜你喜欢
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 2014-05-04
    相关资源
    最近更新 更多