Skip to content

Instantly share code, notes, and snippets.

@anataliocs
Last active September 1, 2022 18:21
  • Star 18 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save anataliocs/715cb36c3604a467d38d to your computer and use it in GitHub Desktop.
Validation messages in messages.properties file for i18n internationalization by locale in spring boot
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@RequestMapping("/")
@ResponseBody
String home() {
return "
}
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.US);
return slr;
}
@Bean
public ReloadableResourceBundleMessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:locale/messages");
messageSource.setCacheSeconds(3600); //refresh cache once per hour
return messageSource;
}
}
public interface MessageByLocaleService {
public String getMessage(String id);
}
@Component
public class MessageByLocaleServiceImpl implements MessageByLocaleService {
@Autowired
private MessageSource messageSource;
@Override
public String getMessage(String id) {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage(id,null,locale);
}
}
user.login.invalid.id=0
user.login.invalid=Your user name or password was invalid
@RestController
@RequestMapping("/user")
public class UserControler {
@Autowired
UserService userService;
@Autowired
MessageByLocaleService messageByLocaleService;
@RequestMapping(value = "/userlogin", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> login(
@RequestBody UserCred userCred)
throws UnsupportedEncodingException {
String invalidLogin = messageByLocaleService.getMessage("user.login.invalid");
}
}
@jmartineztalosdigital
Copy link

great!!! thanks.

My only change @Autowired

@component
public class MessageByLocaleServiceImpl implements MessageByLocaleService {

@Autowired
private MessageSource messageSource;

@sobelfallcayor
Copy link

Great!!!! thanks a lot...
so i used @Autowired

@anataliocs
Copy link
Author

Thanks, updated the code sample.

@zhaozhi406
Copy link

good solution!

@viiicky
Copy link

viiicky commented Jul 29, 2017

Just a quick question: What do we need to have an interface MessageByLocaleService.java?

@chetan7hallan
Copy link

at what location did you place messages_en_us-properties?
and what is significance of "classpath:locale/messages"?

@WenderGalan
Copy link

Thank you brow!! You saved my life LOL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment