Can't get Hibernate Validator working with Spring MessageSource

后端 未结 5 690
北荒
北荒 2021-02-09 17:39

I\'m trying to get Hibernate Validator setup to use messages from a Spring MessageSource. I have the following setup in my messages-context.xml:

<         


        
5条回答
  •  有刺的猬
    2021-02-09 17:43

    Hibernate Validation is not aware of Spring's MessageSource. You will need to implement a MessageInterpolator. It may look something like below:

    public class SpringMessageInterpolator implements MessageInterpolator {
    
        private final MessageResource messageResource;
        private final MessageInterpolator delegate;
    
        public SpringMessageInterpolator(MessageResource messageResource, MessageInterpolator delegate) {
            this.messageResource = messageResource;
            this.delegate = delegate;
        }
    
        @Override
        public String interpolate(String messageTemplate, Context context) {
            Locale locale = Locale.getDefault();
            return interpolate(messageTemplate, context, locale);
        }
    
        @Override
        public String interpolate(String messageTemplate, Context context, Locale locale) {
            try {
                Object[] args = {};
                return databaseMessageResource.getMessage(messageTemplate, args, locale);
            } catch (NoSuchMessageException ex) {
                return delegate.interpolate(messageTemplate, context, locale);
            }
        }
    
    }
    

提交回复
热议问题