LoginSignup
1
3

More than 3 years have passed since last update.

【Spring Boot】独自のプロパティファイルを追加して、env.getProperty()で値を取得したい。

Last updated at Posted at 2020-07-04

デモアプリの構成

デモアプリ構成.png
src/main/resources/test.properties
が追加したプロパティファイル。
このファイルから、値を取得する。

プロパティファイル内.png
プロパティファイル内は、↑の状態。

@PropertySource でEnvironmentにプロパティファイルを追加する

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;

@SpringBootApplication
@PropertySource("classpath:test.properties")
public class PropertyTestApplication {

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

}

@PropertySource()の引数に、プロパティファイルのパスを指定してやれば、Environmentに追加できる。

@PropertySourceは、@Configurationと一緒に宣言する必要があるが、
@SpringBootApplication内で、@Configurationが宣言されているため特別に宣言する必要はない。

@PropertySourceのレファレンスはこちら

env.getProperty()で取得する。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class PropertyGetComponent {

    @Autowired
    Environment env;

    public void printProperty() {
        String value = env.getProperty("test.property.key");
        System.out.println("取得した値は[ " + value + " ] です。");
    }

}

printProperty()の実行結果は↓

取得した値は[ test value ] です。

env.getProperty()で追加したプロパティファイルから、値を取得することができた:blush:

参考にした記事

1
3
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
1
3