我将以下的ReloadableResourceBundleMessageSource
实例化为Spring bean。
<bean id="resourceBundleMessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="locale/messages"/>
<property name="cacheSeconds" value="-1"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
然后在我的服务bean中使用它:
@Qualifier("resourceBundleMessageSource")
private final ReloadableResourceBundleMessageSource messageSource;
@Autowired
public MyClassName(ReloadableResourceBundleMessageSource messageSource) {
this.messageSource = messageSource;
}
public void myMethod() {
String message = messageSource.getMessage("notification.sample", null, getUsersLocale(guest));
// (...)
}
我的resources/locale/messages_en.properties
看起来如下:
notification.sample: This is a sample translation.
但是它引发了以下异常:
[web.1]: SEVERE: Servlet.service() for servlet [mvc-dispatcher] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.context.NoSuchMessageException: No message found under code 'notification.sample' for locale 'en'.] with root cause
[web.1]: org.springframework.context.NoSuchMessageException: No message found under code 'notification.sample' for locale 'en'.
[web.1]: at org.springframework.context.support.AbstractMessageSource.getMessage(AbstractMessageSource.java:155)
[web.1]: at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[web.1]: at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[web.1]: at java.lang.reflect.Method.invoke(Method.java:616)
[web.1]: at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
// (...)
答案 0 :(得分:0)
尝试将@Autowired
注释移动到字段,而不是构造函数。
@Autowired
@Qualifier("resourceBundleMessageSource")
private final ReloadableResourceBundleMessageSource messageSource;
public MyClassName() {
}