How to split Spring Boot message file

Overview

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.

1. Prevent MessageSourceAutoConfiguration from starting

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.

2. Config class

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.

Summary

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

How to split Spring Boot message file
How to bind to property file in Spring Boot
[Spring Boot] How to refer to the property file
How to set Spring Boot + PostgreSQL
How to use ModelMapper (Spring boot)
How to use MyBatis2 (iBatis) with Spring Boot 1.4 (Spring 4)
How to use built-in h2db with spring boot
How to make Spring Boot Docker Image smaller
How to use Spring Boot session attributes (@SessionAttributes)
How to add a classpath in Spring Boot
Spring Boot --How to set session timeout time
Try Spring Boot from 0 to 100.
How to set Dependency Injection (DI) for Spring Boot
How to write a unit test for Spring Boot 2
How to create a Spring Boot project in IntelliJ
[Spring Boot] How to create a project (for beginners)
Introduction to Spring Boot ① ~ DI ~
File upload with Spring Boot
How to use CommandLineRunner in Spring Batch of Spring Boot
How to boot by environment with Spring Boot of Maven
Introduction to Spring Boot Part 1
How to set environment variables in the properties file of Spring boot application
Spring Boot validation message changes
[Ruby] How to split each GraphQL query into a file
How to change application.properties settings at boot time in Spring boot
Extract SQL to property file with jdbcTemplate of spring boot
How to call and use API in Java (Spring Boot)
How to control transactions in Spring Boot without using @Transactional
How to use Lombok in Spring
How to unit test Spring AOP
How to use Spring Data JDBC
[How to install Spring Data Jpa]
Going out of message (Spring boot)
How to convert erb file to haml
Upgrade spring boot from 1.5 series to 2.0 series
[Beginner] How to delete NO FILE
Message cooperation started with Spring Boot
How to make a hinadan for a Spring Boot project using SPRING INITIALIZR
How to create your own Controller corresponding to / error with Spring Boot
How to load a Spring upload file and view its contents
I want to control the default error message of Spring Boot
How to realize huge file upload with Rest Template of Spring
[Xcode] How to add a README.md file
[Introduction to Spring Boot] Form validation check
[Java] How to use the File class
How to delete the wrong migration file
Static file access priority in Spring boot
How to delete the migration file NO FILE
How to include Spring Tool in Eclipse 4.6.3?
Local file download memorandum in Spring Boot
How to add jar file in ScalaIDE
Story when moving from Spring Boot 1.5 to 2.1
Changes when migrating from Spring Boot 1.5 to Spring Boot 2.0
How to achieve file download with Feign
Changes when migrating from Spring Boot 2.0 to Spring Boot 2.2
[Spring MVC] How to pass path variables
How to write Spring AOP pointcut specifier
How to achieve file upload with Feign
Add spring boot and gradle to eclipse
How to apply thymeleaf changes to the browser immediately with #Spring Boot + maven
[Spring Boot] I investigated how to implement post-processing of the received request.