spring-boot-starter-webなど、よく使う依存をまとめたパッケージが提供される@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@SpringBootApplication:設定スキャン、自動設定、Bean登録をまとめて実行SpringApplication.run():内部でTomcatを立ち上げ、Webアプリを動かすspring-boot-starter-webspring-boot-starter-thymeleafspring-boot-starter-data-jpaspring-boot-starter-securityspring-boot-starter-testSpring Initializrという公式ジェネレーターにより、Webブラウザで生成
project-root/
├─ src/
│ ├─ main/
│ │ ├─ java/
│ │ │ └─ com.example.demo/
│ │ │ └─ DemoApplication.java # mainクラス
│ │ ├─ resources/
│ │ │ ├─ application.properties # 設定ファイル
│ │ │ ├─ static/ # 静的ファイル(css, js, img)
│ │ │ └─ templates/ # Thymeleafテンプレート
│ └─ test/
│ └─ java/ # テストコード
└─ pom.xml # 依存関係定義
<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.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.5</version>
</parent>
<dependencies>
<!-- Webアプリ開発 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- テンプレートエンジン -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- テスト用 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
mvn spring-boot:run
java ^jar target/demo-0.0.1-SNAPSHOT.jar
Spring Bootアプリは、基本的に三層構造(MVC)で作られる
com.example.demo
├─ DemoApplication.java # エントリーポイント(main)
├─ controller/ # Webリクエストを受け取る層
├─ service/ # ビジネスロジックを扱う層
└─ repository/ # データアクセスを扱う層(DB関連)
Controller → Service → Repository → Database
Controller:画面やAPIからのリクエストを受け取るService:ビジネスロジック(処理の中心)を記述するRepository:データアクセス(DB操作)を担当→ 次:Controller