Last active
February 23, 2021 23:36
-
-
Save jonikarppinen/0d600b0c82edce890310 to your computer and use it in GitHub Desktop.
Example of using message resources in Spring Boot service layer code, in as simple way as possible (hopefully!). NOTE: this approach supports only a single locale, not dynamically changing it.
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
package com.company.project.components; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.context.MessageSource; | |
import org.springframework.context.support.MessageSourceAccessor; | |
import org.springframework.stereotype.Component; | |
import javax.annotation.PostConstruct; | |
import java.util.Locale; | |
/** | |
* Helper to simplify accessing i18n messages in code. | |
* | |
* This finds messages automatically found from src/main/resources (files named messages_*.properties) | |
* | |
* This example uses hard-coded English locale. | |
* | |
* @author Joni Karppinen | |
* @since 2015-11-02 | |
*/ | |
@Component | |
public class Messages { | |
@Autowired | |
private MessageSource messageSource; | |
private MessageSourceAccessor accessor; | |
@PostConstruct | |
private void init() { | |
accessor = new MessageSourceAccessor(messageSource, Locale.ENGLISH); | |
} | |
public String get(String code) { | |
return accessor.getMessage(code); | |
} | |
} |
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
default.title = Title |
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
package com.company.project.services; | |
import com.company.project.components.Messages; | |
import org.springframework.beans.factory.annotation.Autowired; | |
@Service | |
public class SomeServiceImpl implements SomeService { | |
@Autowired | |
Messages messages; | |
// ... | |
private String getDefaultTitle() { | |
return messages.get("default.title")); | |
} | |
} |
Can you provide a simple unit test for this configuration? I cannot generate a dynamic locale change via this configuration.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Im getting NullPointerException that MessageSource is null