Created
October 6, 2017 16:50
-
-
Save Hromenique/7722328b4953acc8feabc9825aad35c1 to your computer and use it in GitHub Desktop.
Exemplo de configuração de messages (validação) no Spring Boot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.maplink.axiodis.rest.api.endpoint; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.context.MessageSource; | |
import org.springframework.http.ResponseEntity; | |
import org.springframework.web.bind.MethodArgumentNotValidException; | |
import org.springframework.web.bind.annotation.ControllerAdvice; | |
import org.springframework.web.bind.annotation.ExceptionHandler; | |
import java.util.Locale; | |
@ControllerAdvice | |
public class EndpointExceptionHandler{ | |
@Autowired | |
private MessageSource messageSource; | |
@ExceptionHandler(MethodArgumentNotValidException.class) | |
public ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex, Locale locale){ | |
ex.getBindingResult() | |
.getAllErrors().forEach(error -> System.out.println(messageSource.getMessage(error, locale))); | |
return ResponseEntity.badRequest().body(ex.getBindingResult().getAllErrors()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Locale; | |
/** | |
* Messages Configuration regarding information, warnings, errors and others messages types | |
*/ | |
@Configuration | |
public class MessagesConfig { | |
@Bean | |
public MessageSource messageSource(){ | |
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); | |
messageSource.setBasename("classpath:messages/messages"); | |
messageSource.setDefaultEncoding("UTF-8"); | |
messageSource.setFallbackToSystemLocale(false); | |
return messageSource; | |
} | |
@Bean | |
public Validator validatorFactoryBean(MessageSource messageSource){ | |
LocalValidatorFactoryBean validatorFactory = new LocalValidatorFactoryBean(); | |
validatorFactory.setValidationMessageSource(messageSource); | |
return validatorFactory; | |
} | |
@Bean | |
public LocaleResolver localeResolver() { | |
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver(); | |
localeResolver.setDefaultLocale(Locale.US); | |
return localeResolver; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment