This time, I will introduce how to split the message file (.properties) with Spring Boot. If you specify spring.messages.basename in application.properties separated by commas, you can divide it into multiple files, but as the number of files increases, management becomes difficult, so you can dynamically read message files in a specific folder. I did it.
By default, Spring Boot will execute the MessageSourceAutoConfiguration class and generate a Bean for MessageSource if there is a message file in the location specified in spring.messages.basename. Since I want to generate MessageSource by myself this time, do not place resources / messages.properties which is the default value of spring.messages.basename.
Create the Config class with the following contents. I wrote it in Kotlin, but it's the same in Java. This sample reads the message file in resources / i18n. It feels a bit aggressive in terms of processing. .. ..
AppConfig.kt
package ...
import org.springframework.context.MessageSource
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.support.ResourceBundleMessageSource
import org.springframework.core.io.support.ResourcePatternResolver
import org.springframework.util.StringUtils
import java.nio.charset.StandardCharsets
@Configuration
class AppConfig {
/**
*Generate message source
*/
@Bean
fun messageSource(resourcePatternResolver : ResourcePatternResolver): MessageSource {
val messageSource = ResourceBundleMessageSource()
//Encoding set(If necessary)
messageSource.setDefaultEncoding(StandardCharsets.UTF_8)
//Other settings
/*
messageSource.setFallbackToSystemLocale(xxx)
messageSource.setCacheMillis(xxx)
messageSource.setAlwaysUseMessageFormat(xxx)
messageSource.setUseCodeAsDefaultMessage(xxx)
*/
//Get dynamic messages
//Get a list of property files by specifying a pattern
resourcePatternResolver.getResources("classpath*:i18n/*.properties")
.filter { it.isFile }.mapNotNull { it.filename }.forEach {
val baseName = if (it.contains("_")) { //With locale(In the file name"_"It is included)
it.substringBeforeLast("_")
} else { //No locale
it.removeSuffix(".properties")
}
messageSource.addBasenames("i18n/$baseName")
}
}
return messageSource
}
that's all.
It's a bit aggressive, but I hope it helps. Also, I was worried about the performance degradation when the number of file divisions was large, so I created more than 500 files and measured the message acquisition time. The message retrieval time increased in proportion to the number of message files only for the first access, but after the second access (another message key is also possible), the message could be retrieved at high speed. I can't keep up with the internal processing, but I think it contains cache or look-ahead-like processing.
Recommended Posts