LoginSignup
5
4

More than 5 years have passed since last update.

【SpringBoot】プロパティファイルを参照する方法

Last updated at Posted at 2018-11-23

前書き

SpringBootでプロパティファイルの参照の仕方が分からず苦労したことがあったので記事にしました。
SpringBootで"Hello World"できる程度の知識があれば理解できる内容だと思います。

ソースと解説

プロパティファイルを用意

クラスパスを通しているsrc/main/resourcesにプロパティファイルを用意します。
プロパティファイルの名前は何でもいいです。

hogeConfig.properties
hoge.foo=foooooooo
hoge.bar=barrrrrrr

プロパティファイルのBeanを用意

@ComponentをつけてBean(Autowiredできるクラス)にします。
@PropertySourceでプロパティファイルの名前を指定します。
@ConfigurationPropertiesでプロパティのプリフィクスを指定します。
変数とsetterとgetterを記述します。

HogeConfig.java
@Component
@PropertySource("classpath:hogeConfig.properties")
@ConfigurationProperties(prefix = "hoge")
public class HogeConfig {
    private String foo;
    // setter getter は省略
}

プロパティの値を参照する

ControllerやServiceクラスを用意します。
先ほど用意したBeanを@Autowiredでインジェクションします。
インジェクションしたBeanのgetterを呼びます。

HogeController.java
@RestController
public class HogeController {
    @Autowired
    private HogeConfig hogeConfig;

    @GetMapping("/hoge")
    public String hoge() {
        return hogeConfig.getFoo(); // foooooooo
    }
}

※フィールドインジェクションよりコンストラクタインジェクションが推奨されてるみたいです。

参考

Spring @PropertySource example
Spring Bootの@ ConfigurationPropertiesで型安全なプロパティ設定
SpringでField InjectionよりConstructor Injectionが推奨される理由

5
4
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
5
4