[英]Database-driven resource bundle in Spring
我有問題使“數據庫驅動的資源包”工作。 在下面的示例中, TextDAO
在應用程序啟動期間正確注入,但是當訪問messageSource
時,會創建一個新的Messages
對象 - 這就是重點。 如何使這項工作?
<!-- message source -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="someapp.bundle.Messages" />
</bean>
Messages.java
@Component
public class Messages extends ListResourceBundle {
@Autowired
private TextDAO textDAO;
public Messages() {
log.debug("CONSTRUCTOR");
}
@Override
protected Object[][] getContents() {
// loading messages from DB
List<Text> texts = textDAO.findAll(); // textDAO is null
...
}
}
正如Bozho
建議我做的資源包如下所示,但有動態重新加載它的問題。 我認為ReloadableResourceBundleMessageSource用於屬性文件,但也許可以使用它。
public class DatabaseDrivenMessageSource extends ReloadableResourceBundleMessageSource {
private Logger log = LoggerFactory.getLogger(getClass());
private final Map<String, Map<String, String>> properties = new HashMap<String, Map<String, String>>();
private TextDAO textDAO;
@Autowired
public DatabaseDrivenMessageSource(TextDAO textDAO) {
this.textDAO = textDAO;
reload();
}
@Override
protected MessageFormat resolveCode(String code, Locale locale) {
String msg = getText(code, locale);
MessageFormat result = createMessageFormat(msg, locale);
return result;
}
@Override
protected String resolveCodeWithoutArguments(String code, Locale locale) {
return getText(code, locale);
}
private String getText(String code, Locale locale) {
Map<String, String> localized = properties.get(code);
String textForCurrentLanguage = null;
if (localized != null) {
textForCurrentLanguage = localized.get(locale.getLanguage());
if (textForCurrentLanguage == null) {
textForCurrentLanguage = localized.get(Locale.ENGLISH.getLanguage());
}
}
return textForCurrentLanguage != null ? textForCurrentLanguage : code;
}
public void reload() {
properties.clear();
properties.putAll(loadTexts());
}
protected Map<String, Map<String, String>> loadTexts() {
log.debug("loadTexts");
Map<String, Map<String, String>> m = new HashMap<String, Map<String, String>>();
List<Text> texts = textDAO.findAll();
for(Text text: texts) {
Map<String, String> v = new HashMap<String, String>();
v.put("en", text.getEn());
v.put("de", text.getDe());
m.put(text.getKey(), v);
}
return m;
}
}
basename
是一個字符串,所以它不是一個spring bean,因此沒有注入。
你可以嘗試做的是ReloadableResourceBundleMessageSource
並覆蓋那里的一些方法(例如 - getMessage(..)
)。 應該在子類中注入DAO。
ReloadableResourceBundleMessageSource
創建由basename
屬性命名的類的實例。 此實例不會由Spring注入任何依賴項。 這就是您的Messages
對象中的textDAO
字段為空的原因。
此Spring問題具有JDBC支持的示例MessageSource的源代碼,作為附件,您可以使用它來代替ReloadableResourceBundleMessageSource
。
有點舊,但仍然相關...我正在使用帶有JDBC后端的Spring Cloud Config服務器作為i18n的資源包。 零碼。 工作真棒!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.