spring-bootはclasspath下にmessage.properties
という名前のファイルを置けばメッセージプロパティとして使用できる。そうではなく、任意のパス上にファイルを配置したい場合。
準備
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
コード
メッセージプロパティファイルは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;
}
}
調査メモ
spring.messages.basenameでmessage.properties以外の名前にしたり複数のファイルを指定できる。ただし、ここにはclasspath下のファイルしか指定できない。file:files/mymessages
とか書いてもclasspath*:file:files/mymessages.properties
になる。