SpringBoot 設定ファイル リモート読み込み方法【簡単解説】
Spring Bootでは、Spring Cloud Configを使用してリモートで設定ファイルを読み込むことができます。以下はSpring Cloud Configを使用してリモートで設定ファイルを読み込む手順です:
- ポモ.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
- アプリケーションの設定ファイル
- アプリケーションの設定ファイル「application.yml」
spring.cloud.config.uri=http://config-server:8888
- 設定
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
@Configuration
@RefreshScope
public class AppConfig {
@Value("${my.property}")
private String myProperty;
public String getMyProperty() {
return myProperty;
}
}
- アプリケーション設定
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@Autowired
private AppConfig appConfig;
@GetMapping("/myproperty")
public String getMyProperty() {
return appConfig.getMyProperty();
}
}
上記の手順に従うことで、Spring Bootがリモートで設定ファイルを読み取ることが可能になります。設定ファイルが変更された場合、Spring Cloud Busを使用して設定を動的にリフレッシュすることができます。