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?

Spring Bootの基本的な使い方

Posted at

1. Spring Bootの特徴

簡単な設定: XMLや大量の設定ファイルを使用せず、シンプルな構成でスタートできます。

組み込みサーバー: TomcatやJettyが組み込まれており、外部サーバー設定が不要です。

依存関係管理: Spring Boot Starterを使用して、必要な依存関係を一括管理できます。

プロダクション対応: Actuatorを使ってアプリケーションの監視や運用が容易です。

2. 環境構築

必要なもの

JDK (Java Development Kit)

IDE (IntelliJ IDEA, Eclipseなど)

Maven または Gradle

プロジェクトの作成

Spring Initializr (https://start.spring.io/) を使用してプロジェクトを作成します。

必要な依存関係を選択します (例: Spring Web, Spring Data JPA, MySQLなど)。

curl https://start.spring.io/starter.zip -d dependencies=web,data-jpa,mysql -o project.zip
unzip project.zip -d myproject

3. アプリケーションの基本構成

Mainクラス

Spring Bootアプリケーションのエントリーポイントです。

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

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

4. Spring Bootで作成されるファイル

Spring Bootプロジェクトを作成すると、いくつかの基本的なファイルやフォルダーが生成されます。

4.1 src/main/java

Javaコードを格納するフォルダーです。

Applicationクラス: アプリケーションのエントリーポイント。

コントローラー、サービス、リポジトリ、エンティティクラス: アプリケーションの機能に応じて作成。

4.2 src/main/resources

リソースファイルを格納するフォルダーです。

application.propertiesまたはapplication.yml: アプリケーションの設定を記述します。

staticフォルダー: 静的リソース (CSS, JavaScript, 画像など) を格納。

templatesフォルダー: Thymeleafなどのテンプレートエンジンのファイルを配置。

4.3 src/test/java

テストコードを格納するフォルダーです。

単体テストや統合テストを実装します。

4.4 pom.xml (または build.gradle)

ビルドツールの設定ファイル。

依存関係管理: 使用するライブラリを指定。

プラグイン: プロジェクトのビルドや実行に必要な設定を記述。

5. MVCアーキテクチャ

Spring Bootは、Model-View-Controller (MVC) アーキテクチャに基づいてアプリケーションを構築します。

5.1 Model

アプリケーションのデータ構造やビジネスロジックを定義します。エンティティクラスやサービス層が該当します。

package com.example.demo.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;

    // Getters and Setters
}

5.2 View

ユーザーインターフェースを担当します。Spring Bootでは、ThymeleafやReactなどを使用してビューを作成します。

5.3 Controller

リクエストを受け取り、適切なサービスを呼び出して処理結果をビューに返します。

package com.example.demo.controller;

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

@RestController
public class UserController {

    @GetMapping("/users")
    public String getUsers() {
        return "Displaying user list";
    }
}

6. インターフェースの役割

インターフェースは、実装の詳細を隠し、モジュール間の結合度を低くする役割を果たします。Spring Bootでは、以下のような場面でインターフェースが使用されます。

6.1 リポジトリ

データベースとのやり取りを抽象化します。

package com.example.demo.repository;

import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}

6.2 サービス

ビジネスロジックを提供する層で、コントローラーとリポジトリの間をつなぎます。

package com.example.demo.service;

import com.example.demo.entity.User;
import java.util.List;

public interface UserService {
    List<User> getAllUsers();
}

6.3 実装クラス

インターフェースを実装し、実際のロジックを記述します。

package com.example.demo.service.impl;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
}

7. REST APIの作成

コントローラー

Spring Bootを使用して簡単にREST APIを作成できます。

package com.example.demo.controller;

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

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, Spring Boot!";
    }
}

実行

mvn spring-boot:run

ブラウザまたはPostmanでhttp://localhost:8080/helloにアクセスすると、Hello, Spring Boot!が表示されます。

以上がSpring Bootの基本的な使い方です。これを基にアプリケーションを構築してみましょう!

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?