有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (2) 个答案

  1. # 1 楼答案

    首先,你需要自己的消息源。查看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:

    这将主要基于您的db模型。我建议在getBundle()方法中使用@cacable,因为您的本地化不太可能经常更改,而且根据您的数据库模型,它可能会很昂贵。返回的对象只需为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"/>
    
  2. # 2 楼答案

    我想我找到了答案:

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

    还有脸上的表情。xml

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

    谢谢你的帮助