LoginSignup
1
1

Spring bootの構築ツール(Spring Initializr)

Last updated at Posted at 2024-03-26

Spring Initializr

Spring Bootを使った簡単なウェブアプリケーション、Spring Initializrを使用してプロジェクトを生成し、簡単なRESTfulウェブサービスを作成できる。
https://start.spring.io/

構築(Hello World)

プロジェクトのセットアップ

Spring Initializr(https://start.spring.io/) にアクセスします。
以下の設定を行います:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 最新バージョンを選択
  • Project Metadataを入力(Group, Artifactなど)
  • Dependenciesに「Spring Web」を追加
  • 「Generate」ボタンをクリックして、プロジェクトを生成し、ダウンロード

    截屏2024-03-26 19.50.09.png

ビジネスロジックの作成

ダウンロードしたプロジェクトを開き、次のJavaクラスを作成または編集:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
        return String.format("Hello %s!", name);
    }
}

アプリケーションの実行

  1. コマンドラインまたはIDEを使用して、プロジェクトのルートディレクトリに移動する。

  2. 以下のコマンドを実行して、アプリケーションを起動:

./mvnw spring-boot:run

  1. ブラウザを開き、http://localhost:8080/hello にアクセスして、デフォルトの挨拶が表示される

  2. http://localhost:8080/hello?name=YourName にアクセスして、YourName を自分の名前に置き換えます。パーソナライズされた挨拶が表示される

問題対策

以下のエラーメッセージの場合:

package org.springframework.web.bind.annotation does not exist

まず、pom.xmlをチェックする。dependenciesの中に、以下の内容を確認:

    <dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter</artifactId>
	</dependency>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>

	<dependency>
        <groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
    </dependency>


そして、以下のコマンドを実行する:
mvn clean install

以下のメッセージが出ると成功

截屏2024-03-26 20.04.12.png

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