Spring で 設定ファイルから設定値を読み込みます。
環境
- Java 11
- IntelliJ IDEA Community
- Maven
1. Spring Boot の依存関係を追加する
pom.xml に以下を追加します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> <relativePath/> </parent>
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.1.3.RELEASE</version> </dependency> </dependencies>
|
追加後の内容は以下のようになります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.kujilabo</groupId> <artifactId>spring-003</artifactId> <version>1.0.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> <relativePath/> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.1.3.RELEASE</version> </dependency> </dependencies> </project>
|
pom.xml を右クリックし、 Maven -> Reimport をクリックしインポートしておきます。
2. Application を作成する
src/main/java を右クリックし、 New -> Package をクリックし、パッケージを作成します。ここでは com.kujilabo としました。
src/main/java/com.kujilabo を右クリックし、 New -> Java class をクリックし、 Application クラスを作成します。
コードは以下のとおりです。
1 2 3 4 5 6 7 8 9 10 11
| package com.kujilabo;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
|
3. 設定ファイルを作成する
src/main/java を右クリックし、 New -> File をクリックし、 application.yml を作成します。
ファイルの内容は以下のとおりです。
1 2 3 4 5 6 7 8 9
| app: str1: STR1 int1: 123 list1: - abc - def map1: key1: value1 key2: value2
|
4. Config クラスを作成する
@ConfigurationProperties アノテーションを使うと複数の設定値をまとめて読み込むことができます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| package com.kujilabo;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration;
import java.util.List; import java.util.Map;
@Configuration @ConfigurationProperties(prefix = "app") public class AppConfig { public void setStr1(String str1) { System.out.println("str1 = " + str1); // str1 = STR1 }
public void setInt1(Integer int1) { System.out.println("int1 = " + int1); // int1 = 123 }
public void setList1(List<String> list1) { System.out.println("list1 = " + list1); // list1 = [abc, def] }
public void setMap1(Map<String, String> map1) { System.out.println("map1 = " + map1); // map1 = {key1=value1, key2=value2} } }
|