【发布时间】:2016-04-15 15:08:37
【问题描述】:
这是我的 WEB-INF/applicationContext.xml :
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="WEB-INF/resources/messages"/>
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="configurationService" class="com.services.ConfigurationService"/>
<bean id="companyService" class="com.services.CompanyService"/>
<bean id="messageService" class="com.services.MessageService"/>
它在 jsps (spring:message) 中运行良好。问题是我无法检索MessageService 中的消息。我尝试了两种不同的方法:第一种(参见下面的代码)是通过实现org.springframework.context.ApplicationContextAware 使我的MessageService“了解”上下文。上下文在初始化期间由 Spring 加载,但是当我尝试在名称“messageResource”下查找 bean 时,applicationContext.getBean("messageSource") 返回null。
package com.services;
import java.util.Locale;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
public class MessageService implements ApplicationContextAware{
/** MessageService Instance */
private static MessageService instance = null;
/** Spring Message source*/
private ReloadableResourceBundleMessageSource messageSource;
/** Application context */
private ApplicationContext applicationContext;
/** Return MessageService instance */
public final static MessageService getInstance()
{
if (MessageService.instance==null)
{
synchronized(MessageService.class)
{
if (MessageService.instance==null)
MessageService.instance = new MessageService();
}
}
return instance;
}
/** Return a message */
public String getMessage(String messageId)
{
messageSource = (ReloadableResourceBundleMessageSource)applicationContext.getBean("messageSource");
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage(messageId,null, locale);
}
@Override
@Autowired
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
第二种方法是使用FileSystemXmlApplicationContext 在我的MessageService 中加载上下文。 applicationContext.getBean("messageSource") 不再返回 null,但 messageSource.getMessage(messageId,null, locale) 找不到任何消息 (NoSuchMessageException)。消息当然存在于我的 .properties 中
这两个问题看起来都像上下文问题,但我不知道在 .jsp 和 java 类中使用相同的 .properties 文件。另外,我希望在初始化期间在应用程序中加载一次消息,而不必每次在课堂上需要它们时都加载它们。感谢您的帮助!
【问题讨论】: