Skip to content

Instantly share code, notes, and snippets.

@saniaky
Created December 5, 2017 11:10
Show Gist options
  • Save saniaky/c1cbca50202bfa3f16faa0c3e1ceadce to your computer and use it in GitHub Desktop.
Save saniaky/c1cbca50202bfa3f16faa0c3e1ceadce to your computer and use it in GitHub Desktop.
Example of using message resources in Spring Boot service layer code, in as simple way.
import org.springframework.context.MessageSource;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Component;
import java.util.Locale;
/**
* @author saniaky
* @since 12/5/17
*/
@Component
public class Messages {
private final MessageSourceAccessor accessor;
public Messages(MessageSource messageSource) {
this.accessor = new MessageSourceAccessor(messageSource, LocaleContextHolder.getLocale());
}
public String get(String code) {
return accessor.getMessage(code);
}
}
@sayadi
Copy link

sayadi commented Jul 17, 2019

This will always use the default Locale and wouldn't dynamically change with say an "Accept-Language" header for the same reason I mentioned on this similar thread:
https://gist.github.com/jonikarppinen/0d600b0c82edce890310#gistcomment-2972839

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