LoginSignup
3
2

More than 5 years have passed since last update.

spring-bootでファイルパス上のメッセージプロパティをMessageSourceに使う

Posted at

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になる。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2