[JAVA] [Spring] Read a message from a YAML file with MessageSource

Read a message from a YAML file with MessageResource

Motivation

It's troublesome to maintain messages.properties! !! If you touch it with Eclipse, it will be native2ascii without permission, which is a problem! !! 11! !![^ 1]

So let's write in YAML

Purpose

When i18n is supported by an application that uses Spring Framework, a resource file (property file with the extension .properties) such as messages.properties will be used.

It's this kind of guy

message_ja.properties


#Can't you write in a hierarchical structure? No!
site.title=Site title
site.description=Site description
page.header.links.index=Site top
page.header.links.gettingstart=Get started
page.header.links.document=document
page.header.links.community=community

I want to write this like this. [^ 2]

message_ja.yaml


#Can you write in a hierarchical structure? Do I have to do native2ascii? Yay!
site:
  title: "Site title"
  description: "Site description"
page:
  header:
    links:
      index: "Site top"
      gettingstart: "Get started"
      document: "document"
      community: "community"

Even if I googled, I could not find an implementation example of Zubari itself, so I will write it like this.

Project configuration example

A project configuration example for making message resources YAML-enabled. [^ 3] YamlResourceBundle is used to read from the Yaml file. [^ 4]

screenshot-00.png

The contents of each file are as follows. It's simple to do, so you can read it. So detailed explanation is omitted.

build.gradle


buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:2.0.2.RELEASE'
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
	baseName = 'exercise1'
	version =  '0.0.1-SNAPSHOT'
}

repositories {
	mavenCentral()
}

dependencies {
    compile 'org.springframework.boot:spring-boot-devtools'
	compile 'org.springframework.boot:spring-boot-starter-web'
    compile 'org.springframework.boot:spring-boot-starter-thymeleaf'
    compile 'net.rakugakibox.util:yaml-resource-bundle:1.1'
}

sourceCompatibility = '1.8'
targetCompatibility = '1.8'
ext['mainClass'] = 'pkg.exercise1.App'
ext['thymeleaf.version'] = '3.0.9.RELEASE'
ext['thymeleaf-layout-dialect.version'] = '2.3.0'

config/application.yml


spring:
  thymeleaf:
    mode: "HTML"
  messages:
    basename: "i18n/messages"
    encoding: "UTF-8"

i18n/messages.yml


site:
  title: "Excercise"
  description: "This message is output from the YAML resource file"

templates/index.html


<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<title data-th-text="#{site.title}">Title</title>
	</head>
	<body>
		<div>
			<article>
				<h1 data-th-text="#{site.title}">Title</h1>
				<p data-th-text="#{site.description}">This is Index page. Yeah!</p>
				<hr />
				<h2>API</h2>
				<ul>
					<li><a href="#" data-th-href="@{/api/hello}">/api/hello</a></li>
				</ul>
			</article>
		</div>
	</body>
</html>

pkg/exercise1/App.java


package pkg.exercise1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
	public static void main(String... args) {
		SpringApplication.run(App.class, args);
	}
}

pkg/exercise1/configurations/MessageSourceConfig.java


package pkg.exercise1.configurations;

import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;

import net.rakugakibox.util.YamlResourceBundle;

@Configuration
public class MessageSourceConfig {

    @Bean("messageSource")
    public MessageSource messageSource(
            @Value("${spring.messages.basename}") String basename,
            @Value("${spring.messages.encoding}") String encoding
    ) {
        YamlMessageSource ms = new YamlMessageSource();
        ms.setBasename(basename);
        ms.setDefaultEncoding(encoding);
        ms.setAlwaysUseMessageFormat(true);
        ms.setUseCodeAsDefaultMessage(true);
        ms.setFallbackToSystemLocale(true);
        return ms;
    }
}

class YamlMessageSource extends ResourceBundleMessageSource {
    @Override
    protected ResourceBundle doGetBundle(String basename, Locale locale) throws MissingResourceException {
        return ResourceBundle.getBundle(basename, locale, YamlResourceBundle.Control.INSTANCE);
    }
}

pkg/exercise1/controllers/IndexController.java


package pkg.exercise1.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {

	@RequestMapping("/")
	String home() {
		return "index";
	}
}

Browser display

Start the Spring Boot application and try to access [http: // localhost: 8080](http: // localhost: 8080).

screenshot-01.png

I did it. [^ 5]

[^ 1]: Netbeans displays multiple languages side by side, so it's easy to translate and doesn't do native2ascii. He understands the story. However, I have to say that it is honestly subtle if it is easy to use as a development environment because it lacks various functions. [^ 2]: Everyone wants to write like this. I don't want to write, but this page doesn't open. (Mystery) [^ 3]: There are some extra packages, but don't worry. [^ 4]: For this purpose, you only need to use the YamlResourceBundle.Control class. [^ 5]: Confirmed display in English (en) locale. evidence? Hey, that's: smiling_imp:

Recommended Posts

[Spring] Read a message from a YAML file with MessageSource
Read the file under the classpath as a character string with spring
Read a string in a PDF file with Java
File upload with Spring Boot
How to read a library from a JAR file with VS Code << How to not use Maven / Gradle >>
Read dump file with Docker MySQL
Run a batch file from Java
Implement file download with Spring MVC
Convert Excel to Blob with java, save it, read it from DB and output it as a file!
How to open a script file from Ubuntu with VS code
Message cooperation started with Spring Boot
How to check before sending a message to the server with Spring Integration
What is a Spring Boot .original file?
Create a jar file with the command
Create a simple on-demand batch with Spring Batch
Create a MySQL environment with Docker from 0-> 1
Read xlsx file in Java with Selenium
How to split Spring Boot message file
[Rails] How to read the XML file uploaded from the screen with Hash type
I want to be able to read a file using refile with administrate [rails6]
How to create an Excel form using a template file with Spring MVC
From creating a Spring Boot project to running an application with VS Code
I want to read the property file with a file name other than application.yml or application- [profile name] .yml with Spring Boot.
Create a website with Spring Boot + Gradle (jdk1.8.x)
Create a simple search app with Spring Boot
[Android] Read from QR code image with zxing
Read environment variables with ruby ​​file [Super beginner]
Generate kubernentes manifest file from docker-compose.yaml with kompose
DBUnit table definition. Hard to read with yaml! !! !!
Create a web api server with spring boot
Creating a common repository with Spring Data JPA
Build a WEB system with Spring + Doma + H2DB
Create a Spring Boot development environment with docker
Short hand to read JSON body from ServerHttpRequest with self-made WebFilter etc. with Spring WebFlux
Error handling when the maximum file size is exceeded when uploading a file with Spring Boot