2012-06-20 103 views
1

我想模仿Grails解決國際化郵件的方式。Spring MVC ResourceBundleMessageSource XML配置

在WEB-INF/i18n中/我有以下目錄:

管理 /messages_EN.properties

管理 /messages_FR.properties

網站 /messages_EN.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配置文件。

我並不試圖解決與管理員和網站子目錄這個特殊的例子

這可能嗎?

謝謝!

+0

您可能需要擴展'ReloadableResourceBundleMessageSource'來引入某種'discover'屬性,它使消息源搜索'basename'目錄,而不是直接加載文件。 –

+0

@PaulGrime我已根據您的建議實施了一些內容,並編輯了我的問題以包含建議的實施。沿着這些方向的東西應該是正確的?遺漏了什麼?謝謝! – momomo

回答

2

這裏是解決方案:

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> 

享受!