SpringBoot 2.6でプロパティファイル(*.properties)を読み込む

2022年1月21日

環境
Windows10 64bit
Spring Boot 2.6.2
Spring Tool Suite 4
JDK 11

1.ファイル情報の表示
src/main/resources/user.properties
中身は以下の内容です
username=test07
addr=tokyo
num=0120

2.コントローラのソースコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.example.demo;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FileController {
private static final String FILEPATH = "src/main/resources/user.properties";
@GetMapping("/file")
public String funA() throws IOException {
//Pathのオブジェクトを生成
Path filepath = Paths.get(FILEPATH);
List<String> strLst;
//各行を読み込みリスト生成
strLst = Files.readAllLines(filepath);
//for文で各行のデータを出力
for (String st : strLst) {
System.out.println(st);
}
return "arkgame";
}
}
package com.example.demo; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class FileController { private static final String FILEPATH = "src/main/resources/user.properties"; @GetMapping("/file") public String funA() throws IOException { //Pathのオブジェクトを生成 Path filepath = Paths.get(FILEPATH); List<String> strLst; //各行を読み込みリスト生成 strLst = Files.readAllLines(filepath); //for文で各行のデータを出力 for (String st : strLst) { System.out.println(st); } return "arkgame"; } }
package com.example.demo;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FileController {

      private static final String FILEPATH = "src/main/resources/user.properties";

      @GetMapping("/file")
      public String funA() throws IOException {
            //Pathのオブジェクトを生成
            Path filepath = Paths.get(FILEPATH);

            List<String> strLst;
            //各行を読み込みリスト生成
            strLst = Files.readAllLines(filepath);
            //for文で各行のデータを出力
            for (String st : strLst) {
                  System.out.println(st);
            }
            return "arkgame";
      }
}

3.動作確認
プロジェクトを右クリックして、「実行(R)」->「Spring Boot アノテーション」をクリックします
ブラウザで「http://127.0.0.1:8080/file」にアクセスします、画面に「arkgame」が表示されます
コンソール画面に以下の内容が表示されます
username=test07
addr=tokyo
num=0120

Spring Boot

Posted by arkgame