這裏是我的WEB-INF/applicationContext.xml中:如何使用Spring applicationContext從messageSource中檢索消息?
<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"/>
它是在JSP中正常使用(春天:消息)。問題是我無法檢索我的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;
}
}
第二種方法是加載方面,我國MessageService
使用FileSystemXmlApplicationContext
英寸applicationContext.getBean("messageSource")
不再返回null
,但messageSource.getMessage(messageId,null, locale)
找不到任何消息(NoSuchMessageException
)。這些消息當然存在於我的.properties中
這兩個問題看起來都像上下文問題,但我無法弄清楚在.jsp和java類中使用相同的.properties文件。另外,我希望在初始化期間在應用程序中加載一次消息,而不必每次在課堂中都需要加載它們。感謝您的幫助 !
是否必須在''?或者它會在沒有提供的情況下正常工作? –
Chip