ReloadableResourceBundleMessageSource使用通配符

时间:2016-01-11 14:52:56

标签: spring spring-boot angular-translate

进行一些测试后,它看起来 ReloadableResourceBundleMessageSource不支持通配符

假设捆绑文件位于资源中,并具有以下名称:messages.properties,messages_fr.properties等。

此基本名称有效:

setBasename("classpath:/messages");

这个不是

setBasename("classpath*:/messages*");

那么,我该怎么做才能加载匹配给定模式的每个属性文件?

备注:我需要使用ReloadableResourceBundleMessageSource的此实现,因为我希望在REST级别公开给定语言环境的每个属性...以便在客户端使用Angular翻译,如{{3}所述}。

一些想法?非常感谢。

1 个答案:

答案 0 :(得分:2)

正如此post所述,ReloadableResourceBundleMessageSource的refreshProperties方法可以被覆盖,以允许从类路径加载多个资源并对应于给定的模式

让我们用一个具体的例子来使用Spring boot defaults的大部分内容:

public class BaseReloadableResourceBundleMessageSource extends ReloadableResourceBundleMessageSource
    implements InitializingBean {

private static final String PROPERTIES_SUFFIX = ".properties";

private final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

private final Charset encoding = Charset.forName("UTF-8");

@Autowired
private Environment environment;

/**
 * Returns the resource bundle corresponding to the given locale.
 */
public Properties getResourceBundle(Locale locale) {
    clearCacheIncludingAncestors();
    return getMergedProperties(locale).getProperties();
}

@Override
public void afterPropertiesSet() {
    setBasename("classpath*:/" + environment.getProperty("spring.messages.basename", "messages"));
    setDefaultEncoding(environment.getProperty("spring.messages.encoding", encoding.name()));
    setCacheSeconds(environment.getProperty("spring.messages.cache-seconds", int.class, -1));
    setFallbackToSystemLocale(environment.getProperty("spring.messages.fallback-to-system-locale",
            boolean.class, true));
}

@Override
protected PropertiesHolder refreshProperties(String filename, PropertiesHolder propHolder) {
    final Properties properties = new Properties();
    long lastModified = -1;
    try {
        for (Resource resource : resolver.getResources(filename + PROPERTIES_SUFFIX)) {
            final PropertiesHolder holder = super.refreshProperties(cleanPath(resource), propHolder);
            properties.putAll(holder.getProperties());
            if (lastModified < resource.lastModified())
                lastModified = resource.lastModified();
        }
    } catch (IOException ignored) {
        // nothing to do
    }
    return new PropertiesHolder(properties, lastModified);
}

private String cleanPath(Resource resource) throws IOException {
    return resource.getURI().toString().replace(PROPERTIES_SUFFIX, "");
}

}