从 spring ReloadableResourceBundleMessageSource 获取所有密钥

get all keys from spring ReloadableResourceBundleMessageSource

我正在使用 ReloadableResourceBundleMessageSource 来存储我系统的值列表。所以我可以使用 i18N 功能

我在 ReloadableResourceBundleMessageSource 的基本名称中使用了多个资源。 我想将网络 UI 的所有本地化标签传递给客户端(前端),以便在客户端本地缓存。 有没有办法加载我的资源包的整个密钥?

这是我的 ReloadableResourceBundleMessageSource bean 定义:

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>classpath:resource1</value>
            <value>classpath:resource2</value>
        </list>
    </property>
    <property name="cacheSeconds" value="60"/>
    <property name="defaultEncoding" value="UTF-8"/>
    <property name="useCodeAsDefaultMessage" value="true"/>
</bean>

这是我传递所有键的控制器:

@Component
@RequestMapping("/bundle")
public class ResourceBundleController {

    @Autowired
    private MessageSource messageSource;

    @RequestMapping(value = "/locales.js")
    public ModelAndView strings(HttpServletRequest request) {

        // Call the string.jsp view
        return new ModelAndView("/WEB-INF/includes/locales.jsp", "keys", ??? );// HERE IS MY PROBLEM. HOW SHOULD I GET ALL THE KEYS FROM MESSAGESOURCE
    }
}

这是我的客户端资源包密钥:

<%@page contentType="text/javascript" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags"%>

var messages = {};

<c:forEach var="key" items="${keys}">
    messages["<spring:message text='${key}' javaScriptEscape='true'/>"] = "<spring:message code='${key}' javaScriptEscape='true' />";
</c:forEach>

我们将不胜感激。

有关 spring 配置的更新信息,有关资源包的缓存

你可以做这样的事情:

您自己实现的 ReloadableResourceBundleMessageSource

public class ExposedResourceMessageBundleSource extends ReloadableResourceBundleMessageSource {

    private static final Logger LOGGER = Logger.getLogger(ExposedResourceMessageBundleSource.class);

    @Override
    protected Properties loadProperties(Resource resource, String fileName) throws IOException {

        LOGGER.info("Load " + fileName);
        return super.loadProperties(resource, fileName);
    }

    /**
     * Gets all messages for presented Locale.
     * @param locale user request's locale
     * @return all messages
     */
    public Properties getMessages(Locale locale){
        return getMergedProperties(locale).getProperties();
    }
}

处理资源操作的服务定义:

public interface MessageResolveService extends MessageSourceAware{
    String getMessage(String key, Object[] argumentsForKey, Locale locale);
    Map<String,String> getMessages(Locale locale);
}

和实现:

    @Service
    public class MessageResolverServiceImpl implements MessageResolveService{
        private static final Logger LOGGER = Logger.getLogger(MessageResolverServiceImpl.class);

        private MessageSource messageSource;

        @Override
        public void setMessageSource(MessageSource messageSource) {
            LOGGER.info("Messages i18n injected");
            this.messageSource = messageSource;
        }

        public String getMessage(String key, Object[] arguments, Locale locale){
            String message = "";
            try{
                message = messageSource.getMessage(key,arguments,locale);
            } catch(NoSuchMessageException e){
                message = key;
                LOGGER.warn("No message found: "+key);
            }
            return message;
        }

        public Map<String,String> getMessages(Locale locale){
            Properties properties =  ((XmlWebApplicationContext)messageSource).getBean("messageSource",
                    ExposedResourceMessageBundleSource.class).getMessages(locale);
            Map<String,String> messagesMap = new HashMap<String,String>();
            for(Map.Entry<Object,Object> entry: properties.entrySet()){
                if(entry.getKey() != null && entry.getValue() != null) {
                    messagesMap.put(entry.getKey().toString(), entry.getValue().toString());
                }
            }
            return messagesMap;
        }
    }

Spring配置:

<bean id="messageSource" class="your.package.ExposedResourceMessageBundleSource">
          <property name="basenames">
           <list>
                <value>classpath:yourFileName</value>
                <value>classpath:yourNextFileName</value>
            </list>
          </property>
          <property name="defaultEncoding" value="UTF-8"/>
          <property name="cacheSeconds" value="10"/> //If you want reload message every couple seconds. In this case every 10 seconds.
</bean>

还有你的@Controller(类似于此):

@Component
@RequestMapping("/bundle")
public class ResourceBundleController {

    @Autowired
    private MessageResolveService messageResolveService;


    @RequestMapping(value = "/locales.js")
    public ModelAndView strings(HttpServletRequest request) {

        // Call the string.jsp view
        return new ModelAndView("/WEB-INF/includes/locales.jsp", "keys", messageResolverService.getMessages(LocaleContextHolder.getLocale()));
}