LoginSignup
0
0

More than 5 years have passed since last update.

[Spring Boot] URLに含まれる文字列から動的にプロパティを取得する方法

Posted at

Environmentを利用して動的にプロパティファイルから値を取得する。

バージョン

spring boot 2.0.3.RELEASE

プロパティファイル

application.properties
sample.name=hoge
sample.age=20

Environmentを利用したConfigurationクラス

EnvironmentをインジェクションしてgetPropertyメソッドを呼び出す。

SampleProperty.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
@Configuration
// @PropertySourceでプロパティファイルの場所を指定
@PropertySource("classpath:/application.properties")
public class SampleProperty {

    // Environmentをインジェクション
    @Autowired
    private Environment env;

    public String get(String key) {
        // Environmentからプロパティ値を取得
        return env.getProperty("sample." + key);
    }

}

RestController(Configurationクラスを呼び出すクラス)

URLに含まれるパスをkeyとしてConfigurationクラスから値を取得する。

SampleController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@Component
@RestController
public class SampleController {

    @Autowired
    private SampleProperty prop;

    @GetMapping(path = "/user/{key}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getUser(@PathVariable String key) {

        String result = prop.get(key);

        if (result == null) {
            result = "値が取得できませんでした。";
        }

        return result;
    }
}

動作確認

ブラウザからhttp://localhost:8080/user/name にアクセス

spring1.png

ブラウザからhttp://localhost:8080/user/age にアクセス
spring2.png

0
0
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
0
0