Skip to content

Instantly share code, notes, and snippets.

@saniaky
Created December 5, 2017 11:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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);
}
}
@Knarra00
Copy link

Hi,

How i can do the unit test for this, do we need have separate message.properties ? how to inject Mock Messages

@sangimed
Copy link

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 ?

@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