Just for the record, for the predefined annotation stuff it seems to me (I'm using spring 3.0.3) that a custom interpolator is not needed. I am able to specify custom codes in the annotations simply by wrapping them in curly braces.
Code:
@Pattern(regexp="[0-9]+", message="{someerror.code}"
Also, default messages for the annotations can be defined as
Code:
<constraint_name>.<command_name>.<field_name>
eg
Size=the {0} field must be between {2} and {4} characters long
or
Size.book.description=the book''s description must be between {2} and {4} characters long
CORRECTION: It appears the message="{someerror.code}" works only if the validation messages are in the spec's defined ValidationMessages.properties. If you have them in your messages.properties, perhaps this is the appropriate class to use:
Code:
package com.foo.web.validation;
import java.util.Locale;
import javax.validation.MessageInterpolator;
import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.NoSuchMessageException;
public class CustomSpringMessageSourceInterpolator extends ResourceBundleMessageInterpolator implements MessageInterpolator, MessageSourceAware, InitializingBean {
@Autowired
private MessageSource messageSource;
@Override
public String interpolate(String messageTemplate, Context context) {
try {
return messageSource.getMessage(messageTemplate, new Object[]{}, Locale.getDefault());
} catch (NoSuchMessageException e) {
return super.interpolate(messageTemplate, context);
}
}
@Override
public String interpolate(String messageTemplate, Context context, Locale locale) {
try {
return messageSource.getMessage(messageTemplate, new Object[]{}, locale);
} catch (NoSuchMessageException e) {
return super.interpolate(messageTemplate, context, locale);
}
}
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
public void afterPropertiesSet() throws Exception {
if (messageSource == null) {
throw new IllegalStateException("MessageSource was not injected, could not initialize "
+ this.getClass().getSimpleName());
}
}
}