messages.properties taken from db [duplicate]

血红的双手。 提交于 2019-12-22 14:58:28

问题


Possible Duplicate:
Design question regarding Java EE entity with multiple language support

I'm working on i18n of JSF application. I need all standard jsf messages that are usually located in messages.properties to be taken from database. Is there some simple way to do it?

Thanks.


回答1:


I think I found the answer:

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

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

and in FacesConfig.xml

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

Thank You for help.




回答2:


First, you will need your own MessageSource. Take a look at AbstractMessageSource and extend it:

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

Your store must return a ResourceBundle:

This will largely be based off your db model. I would recommend using @Cachable on the getBundle() method, as your localizations are not likely to change often, and depending on your DB model, it may be expensive. The object returned needs only to implement the following methods for ResourceBundle:

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

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

Finally, you need to register your MessageSource bean in your configuration:

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


来源:https://stackoverflow.com/questions/9080474/messages-properties-taken-from-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!