小编典典

Spring MVC ResourceBundleMessageSource XML配置

spring-mvc

我想模仿Grails解决i18n消息的方式。

在WEB-INF / i18n /中,我具有以下目录:

管理员 /messages_EN.properties

管理员 /messages_FR.properties

网站 /messages_ZH.properties

网站 /messages_FR.properties

在此示例中,请忽略语言结尾(EN和FR)

在我的xml配置中,我目前有:

<!-- Register the welcome.properties -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  <property name="defaultEncoding" value="utf-8" />
  <property name="basename" value="/WEB-INF/i18n/" />
</bean>

我在这里寻找的是一种告诉Spring在i18n下查找.properties文件的方法,但没有明确告诉它每个子目录是什么。这是 没有 一个
列表基本名称 ,它指向 / WEB-INF / i18n中/管理// WEB-INF / i18n中/网站/

我希望WEB-INF / i18n /目录是动态的,并且可以创建捆绑包(目录),而无需重新修改xml配置文件。

我不是想用admin和website子目录来解决这个特定的例子

这可能吗?

谢谢!


阅读 461

收藏
2020-06-01

共1个答案

小编典典

解决方法如下:

package com.mypackage.core.src;

import java.io.File;
import java.util.ArrayList;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

public class UnderDirectoryReloadableResourceBundleMessageSource extends ReloadableResourceBundleMessageSource {

    @Autowired
    ServletContext servletContext;

    public void setWorkingDirectory(String directoryPath) {
        File rootDir = new File( servletContext.getRealPath(directoryPath) );
        ArrayList<String> baseNames = new ArrayList<String>();
        iterateScanDirectoryAndAddBaseNames(baseNames, rootDir);
        setBasenames(baseNames.toArray(new String[baseNames.size()]));
    }

    private void iterateScanDirectoryAndAddBaseNames(ArrayList<String> baseNames, File directory) {
        File[] files = directory.listFiles();

        for (File file : files) {
            if (file.isDirectory()) {
                iterateScanDirectoryAndAddBaseNames(baseNames, file);
            } else {
                if (file.getName().endsWith(".properties")) {
                    String filePath = file.getAbsolutePath().replaceAll("\\\\", "/").replaceAll(".properties$", "");
                    filePath = filePath.substring(filePath.indexOf("/WEB-INF/"), filePath.length());
                    baseNames.add(filePath);
                    System.out.println("Added file to baseNames: " + filePath);
                }
            }
        }
    }

}

XML配置:

<bean id="messageSource" class="com.mypackage.core.src.UnderDirectoryReloadableResourceBundleMessageSource">
  <property name="defaultEncoding" value="utf-8" />
  <property name="workingDirectory" value="/WEB-INF/webspring/i18n" />
  <property name="cacheSeconds" value="3" />
  <property name="fallbackToSystemLocale" value="false" />
</bean>

请享用!

2020-06-01