[英]Load resource bundle at runtime
這是我想要實現的。 我們有一個在Tivoli Domino服務器上作為servlet運行的應用程序。 該應用程序使用資源束根據瀏覽器語言獲取翻譯后的消息和標簽。
我們希望使客戶能夠覆蓋某些值。 我們無法在運行時修改.jar中的bundle_lang.properties文件。 因此,該想法是提供附加的bundleCustom_lang.properties文件以及.jar文件
可以使用以下命令在運行時加載該捆綁包
private static void addToClassPath(String s) throws Exception {
File file = new File(s);
URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader();
java.lang.reflect.Method m = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
m.setAccessible(true);
m.invoke(cl, new Object[] { file.toURI().toURL() });
}
到目前為止,一切都很好,這在Eclipse中有效。 在這里,我在工作區之外的目錄中有bundleCustom文件(/ volumes / DATA / Temp /)
一旦附加ResourceBundle可用,我們將首先檢查此捆綁包中的密鑰。 如果返回一個值,則此值將用於轉換。 如果沒有返回值,或者文件不存在,則使用.jar包中的值。
我的完整代碼在這里
public class BundleTest2 {
static final String CUSTOM_BUNDLE_PATH = "/volumes/DATA/Temp/";
static final String CUSTOM_BUNDLE_MODIFIER = "Custom";
public static void main(String[] args) {
try {
addToClassPath(CUSTOM_BUNDLE_PATH);
System.out.println(_getTranslation("LabelBundle", "OutlineUsersAllVIP"));
} catch (Exception e) {
}
}
private static String _getTranslation(String bundle, String translation) {
return _getTranslation0(bundle, new Locale("de"), translation);
}
private static String _getTranslation0(String bundle, Locale locale, String key) {
String s = null;
try {
try {
ResourceBundle custom = ResourceBundle.getBundle(bundle + CUSTOM_BUNDLE_MODIFIER, locale);
if (custom.containsKey(key)) {
s = custom.getString(key);
}
} catch (MissingResourceException re) {
System.out.println("CANNOT FIND CUSTOM RESOURCE BUNDLE: " + bundle + CUSTOM_BUNDLE_MODIFIER);
}
if (null == s || "".equals(s)) {
s = ResourceBundle.getBundle(bundle, locale).getString(key);
}
} catch (Exception e) {
}
return s;
}
private static void addToClassPath(String s) throws Exception {
File file = new File(s);
URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader();
java.lang.reflect.Method m = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
m.setAccessible(true);
m.invoke(cl, new Object[] { file.toURI().toURL() });
}
}
當我從servlet內部嘗試相同操作時,會收到MissingResourceException。
我還嘗試了將.properties文件放入customization.jar中,並在調用addToClassPath()時提供完整路徑(包括.jar)。 顯然,customization.jar已加載(它已鎖定在文件系統中),但是我仍然收到MissingResourceException。
我們已經在addToClassPath中使用了相同的代碼來加載Db2驅動程序,並且該程序可以按預期工作。
我想念什么?
為什么不使用數據庫存儲替代翻譯? 在應用程序的本地部署中堅持由客戶端創建的內容通常不是一個好主意,如果重新部署應用程序會發生什么,這些資源會被刪除嗎? 如果必須運行應用程序的另一個節點怎么辦,您將如何復制自定義屬性文件?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.