Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Feb 26, 2018

Hi,

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

@sangimed

This comment has been minimized.

Copy link

commented Jul 16, 2018

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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.