Я занимаюсь разработкой веб-приложения с весенней загрузкой 2.1.3. Используя проверку бина, я могу выдать исключение с сообщениями, определенными в message.properties. Например, возраст человека не должен быть нулевым, тогда у меня есть следующее:
message.properties
person.age=A person's age
person.age.notNull={person.age} should not be null
Person
public class Person{
@NotNull(message = "{person.age.notNull}")
private Integer age;
private String job;
// constructor, getter, setter ...
}
Beans
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
@Bean
public LocalValidatorFactoryBean validator() {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource());
return bean;
}
Проверка бина человека
@Autowired Validator validator;
......
Set<ConstraintViolation<Person>> violationSet = validator.validate(person);
if (!violationSet.isEmpty()) {
// throw exception
}
Благодаря Hibernate сообщение person.age.notNull
разрешено, поэтому я получаю "Возраст человека не должен быть нулевым"
Я однаконе может получить то же сообщение с помощью messageSource.getMessage("person.age.notNull", new Object[]{}, LocaleContextHolder.getLocale())
, но «{person.age} не должен быть нулевым»
Если я изменю сообщение на person.age.notNull={person.age} should not be null, {0}
и вызову messageSource.getMessage("person.age.notNull", new Object[]{"please give it a value"}, LocaleContextHolder.getLocale())
, выдается следующее исключение
java.lang.IllegalArgumentException: can't parse argument number: person.age
at java.text.MessageFormat.makeFormat(MessageFormat.java:1429)
at java.text.MessageFormat.applyPattern(MessageFormat.java:479)
at java.text.MessageFormat.<init>(MessageFormat.java:380)
at org.springframework.context.support.MessageSourceSupport.createMessageFormat(MessageSourceSupport.java:159)
at org.springframework.context.support.ReloadableResourceBundleMessageSource$PropertiesHolder.getMessageFormat(ReloadableResourceBundleMessageSource.java:617)
at org.springframework.context.support.ReloadableResourceBundleMessageSource.resolveCode(ReloadableResourceBundleMessageSource.java:206)
at org.springframework.context.support.AbstractMessageSource.getMessageInternal(AbstractMessageSource.java:224)
at org.springframework.context.support.AbstractMessageSource.getMessage(AbstractMessageSource.java:153)
......
Как я знаю, Spring разрешает сообщения, используя спящий режим. Могу ли я узнать, как я могу разрешить свое сообщение таким же образом?