0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ConfigurationPropertiesでmapにプロパティをバインド

Posted at

たとえば、以下のように同一の親キーを持つプロパティをMapにバインドしたい、とする。

prefecture.kanagwa=KANAGAWA
prefecture.tokyo=TOKYO
prefecture.chiba=CHIBA
plugins {
	id 'java'
	id 'org.springframework.boot' version '3.4.5'
	id 'io.spring.dependency-management' version '1.1.7'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'

java {
	toolchain {
		languageVersion = JavaLanguageVersion.of(21)
	}
}

configurations {
	compileOnly {
		extendsFrom annotationProcessor
	}
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

tasks.named('test') {
	useJUnitPlatform()
}
import java.util.Map;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties
@Data
public class PrefectureConfig {

  Map<String, String> prefecture;
}

上記にすると prefecture は以下になる。

{kanagwa=KANAGAWA, tokyo=TOKYO, chiba=CHIBA}

もし、以下のようにプロパティが特定のprefix下であれば、

japan.prefecture.kanagwa=KANAGAWA
japan.prefecture.tokyo=TOKYO
japan.prefecture.chiba=CHIBA

以下のように変更すれば同一の結果が得られる。

@ConfigurationProperties("japan")
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?