Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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");
}
}

great!!! thanks.

My only change @Autowired

@component
public class MessageByLocaleServiceImpl implements MessageByLocaleService {

@Autowired
private MessageSource messageSource;

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

Owner

anataliocs commented Jul 13, 2017

Thanks, updated the code sample.

good solution!

viiicky commented Jul 29, 2017

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

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