问题
I mixed both org.springframework.validation together with JSR-303 annotation.
JSR-303 annotation:
public class Model{
private String type;
private State state;
@NotNull(message = "{comment.notnull}")
private String comment;
}
Spring framework validation:
@Component
public class ModelValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Model.class.equals(clazz);
}
@Override
public void validate(Object obj, Errors errors) {
Model model = (Model) obj;
if (eventModel.getState() == null) {
errors.reject("state", "error.state.invalidState");
}
}
}
My ValidationMessages_en.properties
error.state.invalidState=Invalid state.
comment.notnull=Comment not null.
Then my configuration:
@Configuration
public class ValidationConfig {
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("ValidationMessages");
return messageSource;
}
}
When i run my springboot application, the interpolation works for JSR-303, but not the custom validator, did i miss something? Tried for long time but can't figure out.
Result:
"error_messages": [
{
"error_message": "Comment not null"
},
{
"error_message": "error.state.invalidState"
}
]
回答1:
I am not sure if there is any easy way but eventually I had to do like this ,
Added below component ,
import java.util.Locale;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Component;
@Component
public class Messages {
@Autowired
private MessageSource messageSource;
private MessageSourceAccessor accessor;
@PostConstruct
private void init() {
accessor = new MessageSourceAccessor(messageSource, Locale.ENGLISH);
}
public String get(String property) {
return accessor.getMessage(property);
}
}
Then I would inject this component in my validator & use above get("error.state.invalidState")
method of this class instead of error.state.invalidState
directly.
messageSource
is the bean that you already defined in system. Locale can be externalized and default locale can be set with another configuration.
MessageSourceAccessor
has lots of overloaded methods, you can directly expose that too if wish to provide those options.
回答2:
I think you have confused between two methods:
reject(String errorCode, String defaultMessage)
rejectValue(String field, String errorCode)
As your configuration seems fine, just doing the following should solve your problem:
errors.rejectValue("state", "error.state.invalidState");
Or
errors.reject("error.state.invalidState", "Some default message to fallback!");
来源:https://stackoverflow.com/questions/53649353/springboot-error-message-interpolation-not-working-for-custom-validator