Spring MessageSource没有从属性文件

时间:2015-08-08 10:49:21

标签: java spring spring-mvc

我做了一些谷歌搜索,发现我的问题出现了很多次,但我已经尝试了所有建议的解决方案,但它仍然不适合我

我一直得到这个例外:

org.springframework.context.NoSuchMessageException: No message found under code 'error.null.firstname' for locale 'en'.

这是我的设置 在我的dispatcher-servlet.xml文件中,我有:

<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value = "error"/>
</bean>

我在src / main / resources /下直接有一个属性文件(error_en.properties) 它确实包含以下行:

error.null.firstname=Firstname cannot be null

在我的代码中我正在尝试:  

    @Autowired
    private MessageSource messageSource;
    ...
    System.out.println(messageSource.getMessage("error.null.firstname", null, Locale.ENGLISH));

但是上面没有用,并且给了我上面提到的例外

我尝试在value属性中将“classpath:”添加到'value'前缀,但这对我不起作用。 我确保文件名'error'与value属性匹配,因为我知道'_en'将由Spring Framework处理。

我看不出我错过了什么?

1 个答案:

答案 0 :(得分:1)

经过几天的实验/调试后,终于弄明白了问题所在。

我正在自动装配MessageSource的类实际上属于不同的上下文。

我的messageSource bean定义是在我的dispatcher-Servlet.xml上下文文件中声明的,因为我正在开发一个Web应用程序。

我的业务类是在application-context.xml中声明的,因此无法找到MessageSource。

我将所有内容都移到了dispatcher-Servlet.xml文件后就可以了。可能不是一个优雅的解决方案,但这解决了我的问题。

感谢之前的所有帮助