Use message property on file path for MessageSource in spring-boot

spring-boot can be used as a message property by putting a file named `` `message.properties``` under the classpath. Instead, if you want to put the file on any path.

Preparation

pom.xml


	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.1.RELEASE</version>
	</parent>

code

Place the message properties file in files / mymessages.properties.

files/mymessages.properties


hoge.message=foobar

Application.java


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

@SpringBootApplication
public class Application implements CommandLineRunner {

	@Autowired
	@Lazy
	MessageSource messageSource;

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		String hoge = messageSource.getMessage("hoge.message", null, null);
		System.out.println(hoge);
	}

	@Bean
	public MessageSource messageSource() {
		ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
		messageSource.setBasename("file:files/mymessages");
		return messageSource;
	}
}

Survey memo

You can specify a name other than message.properties or specify multiple files in spring.messages.basename. However, only files under the classpath can be specified here. Even if you write `file: files / mymessages```, it will be `classpath *: file: files / mymessages.properties```.

Recommended Posts

Use message property on file path for MessageSource in spring-boot
Use completion in Eclipse on mac
Use docker in proxy environment on ubuntu 20.04.1