我在这里尝试了答案中的步骤:HibernateValidator,自定义ResourceBundleLocator和Spring
但是仍然只是{location.title.notEmpty}作为输出而不是消息。
{location.title.notEmpty}
dispatcher-servlet.xml
<bean name="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="validationMessageSource"> <ref bean="resourceBundleLocator"/> </property> </bean> <bean name="resourceBundleLocator" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basenames"> <list> <value>/WEB-INF/validationMessages</value> </list> </property> </bean>
/WEB-INF/validationMessages.properties:
location.title.notEmpty=My custom message
表格(上课地点)
@NotEmpty( message = "{location.title.notEmpty}" ) private String title;
这是怎么了
得到它了!:-)
我在我的计算机中添加了以下bean而不是上面提到的两个dispatcher-servlet.xml:
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/validationMessages" /> </bean>
然后,在我的validationMessages.properties中,使用以下语法:
NotEmpty.location.title=My custom Message
我猜这是原因:我使用了Hibernate验证注释(不是javax注释)
对于一般情况,消息文件的语法应类似于
[ConstraintName].[ClassName].[FieldName]=[Message]
希望这可以帮助其他人;-)
要从spring控制器访问消息,只需将其添加@Autowired private MessageSource messageSource;为类字段并使用messageSource.getMessage方法即可。因为我只使用一种语言环境messageSource.getMessage("NotEmpty.location.title", null, null )
@Autowired private MessageSource messageSource;
messageSource.getMessage
messageSource.getMessage("NotEmpty.location.title", null, null )