Created
December 5, 2017 11:10
-
-
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.
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 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); | |
} | |
} |
Hi,
I get org.springframework.context.NoSuchMessageException: No message found under code 'hello.world' for locale 'fr_FR'.
with \src\main\resources\messages.properties.
I verified in debug mode that LocaleContextHolder.getLocale() = "fr_FR"
I tried with different names messages_fr.properties messages_FR.properties messages_fr_FR.properties but none of them worked.
Any clue ?
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
Hi,
How i can do the unit test for this, do we need have separate message.properties ? how to inject Mock Messages