Spring Core
Spring Frameworkの中核モジュールで、依存性注入(DI)とアスペクト指向プログラミング(AOP)を提供します。
📌 主な機能:
- IoC(制御の反転)コンテナ
- 依存性注入(DI)によるオブジェクト管理
- Beanのライフサイクル管理
- AOPによるクロスカッティングコンサーン
Bean定義の例:
@Configuration
public class AppConfig {
@Bean
public UserService userService() {
return new UserServiceImpl();
}
@Bean
public LoggingAspect loggingAspect() {
return new LoggingAspect();
}
}
Spring Core アノテーション
アノテーション | 説明 |
---|---|
@Configuration | Spring設定クラスの宣言 |
@Bean | Springコンテナで管理するオブジェクトの定義 |
@Component | 汎用的なSpringコンポーネントの宣言 |
@Service | ビジネスロジッククラスの宣言 |
@Repository | データアクセスクラスの宣言 |
@Autowired | 依存性の自動注入 |
@Qualifier | 同じ型のBean間で注入対象を特定 |
@Scope | Beanのスコープ指定(singleton, prototype等) |
💡 スコープの種類:
- singleton: アプリケーション内で1つのインスタンス(デフォルト)
- prototype: 要求ごとに新しいインスタンス
- request: HTTPリクエストごとに1つのインスタンス
- session: HTTPセッションごとに1つのインスタンス
Spring Data JDBC
Spring Data JDBCはデータベースアクセスを簡素化し、リポジトリパターンによる高レベルな抽象化を提供します。
リポジトリインターフェース:
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
// 名前に基づいて検索するカスタムメソッド
List<User> findByName(String name);
// メールアドレスで検索
Optional<User> findByEmail(String email);
// カスタムクエリの定義
@Query("SELECT * FROM users WHERE age > :age")
List<User> findUsersOlderThan(@Param("age") int age);
}
エンティティクラス:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table("users")
public class User {
@Id
private Long id;
private String name;
private String email;
private Integer age;
// リレーションマッピング
@MappedCollection(idColumn = "user_id")
private Set<Address> addresses = new HashSet<>();
}
📋 Spring Data JDBCの特徴:
- リポジトリパターンによる宣言的なデータアクセス
- CRUD操作のメソッドが自動生成
- データベース構造に密接にマッピング
- 軽量なORM機能
CrudRepositoryの主なメソッド:
操作 | メソッド | 説明 |
---|---|---|
作成/更新 | save(T entity) |
エンティティを保存/更新 |
saveAll(Iterable<T> entities) |
複数エンティティを保存/更新 | |
読み取り | findById(ID id) |
IDでエンティティを検索 |
findAll() |
すべてのエンティティを取得 | |
findAllById(Iterable<ID> ids) |
複数IDでエンティティを検索 | |
count() |
エンティティの総数を取得 | |
existsById(ID id) |
エンティティの存在確認 | |
削除 | deleteById(ID id) |
IDでエンティティを削除 |
delete(T entity) |
エンティティを削除 | |
deleteAllById(Iterable<ID> ids) |
複数IDでエンティティを削除 | |
deleteAll() |
すべてのエンティティを削除 |
Gradleビルド設定
Spring BootとGradleを使ったプロジェクト構成と依存関係管理。
基本的なbuild.gradle:
plugins {
id 'org.springframework.boot' version '3.2.3'
id 'io.spring.dependency-management' version '1.1.4'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
// Spring Core
implementation 'org.springframework.boot:spring-boot-starter'
// Spring MVC + Thymeleaf
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
// Spring Data JDBC
implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
// Validation
implementation 'org.springframework.boot:spring-boot-starter-validation'
// Lombok
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
// Database
runtimeOnly 'com.h2database:h2'
// Test
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
Spring MVC
Spring MVCはWebアプリケーション開発のためのフレームワークです。
基本的なコントローラー:
@Controller
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public String listUsers(Model model) {
List users = userService.findAll();
model.addAttribute("users", users);
return "users/list"; // Thymeleafテンプレート名
}
@GetMapping("/{id}")
public String viewUser(@PathVariable Long id, Model model) {
User user = userService.findById(id);
model.addAttribute("user", user);
return "users/view";
}
@PostMapping
public String saveUser(@Valid User user,
BindingResult result,
Model model) {
if (result.hasErrors()) {
return "users/form";
}
userService.save(user);
return "redirect:/users";
}
}
HTTPメソッド:
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
MVCコンポーネント:
Model
View
Controller
リクエストパラメータ
Spring MVCでは様々な方法でリクエストデータを受け取れます。
1. パスパラメータ
@GetMapping("/users/{id}")
public String getUser(@PathVariable Long id) {
// /users/1 のようなURLでidは1になる
return "user/detail";
}
2. クエリパラメータ
@GetMapping("/search")
public String search(@RequestParam String keyword,
@RequestParam(defaultValue = "10") int limit) {
// /search?keyword=spring&limit=20
return "search/results";
}
3. フォームデータ
@PostMapping("/register")
public String register(@ModelAttribute UserForm form) {
// formタグからのPOSTリクエスト
return "redirect:/success";
}
4. JSONデータ
@PostMapping("/api/users")
@ResponseBody
public User createUser(@RequestBody User user) {
// JSONからUserオブジェクトへの自動変換
return userService.save(user);
}
Thymeleaf
ThymeleafはモダンなサーバーサイドJavaテンプレートエンジンです。
基本的な使用例(users/list.html):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>ユーザー一覧</title>
</head>
<body>
<h1>ユーザー一覧</h1>
<!-- 条件分岐 -->
<div th:if="${users.isEmpty()}">
<p>ユーザーはいません</p>
</div>
<!-- リスト繰り返し -->
<table th:unless="${users.isEmpty()}">
<tr>
<th>ID</th>
<th>名前</th>
<th>メール</th>
<th>操作</th>
</tr>
<tr th:each="user : ${users}">
<td th:text="${user.id}">1</td>
<td th:text="${user.name}">名前</td>
<td th:text="${user.email}">メール</td>
<td>
<!-- リンク生成 -->
<a th:href="@{/users/{id}(id=${user.id})}">詳細</a>
</td>
</tr>
</table>
<!-- フォーム -->
<form th:action="@{/users}" th:object="${newUser}" method="post">
<input type="text" th:field="*{name}" />
<span th:if="${#fields.hasErrors('name')}"
th:errors="*{name}">名前エラー</span>
<button type="submit">登録</button>
</form>
</body>
</html>
📝 Thymeleaf主要機能:
- th:text: テキスト内容の置換
- th:each: 繰り返し処理
- th:if/unless: 条件分岐
- th:href/@{}: URL生成
- th:object/*{}: フォーム連携
バリデーション
Spring BootはBean Validationをサポートし、データ検証を簡単に実装できます。
1. モデル定義
public class UserForm {
@NotBlank(message = "名前は必須です")
@Size(min = 2, max = 50, message = "名前は2〜50文字で入力してください")
private String name;
@NotBlank(message = "メールアドレスは必須です")
@Email(message = "有効なメールアドレスを入力してください")
private String email;
@NotNull(message = "年齢は必須です")
@Min(value = 18, message = "年齢は18歳以上である必要があります")
private Integer age;
// ゲッター、セッター
}
2. コントローラーでの利用
@Controller
public class UserController {
@PostMapping("/users")
public String register(@Valid UserForm form,
BindingResult result,
Model model) {
if (result.hasErrors()) {
// バリデーションエラーあり
return "users/form";
}
// 登録処理
userService.register(form);
return "redirect:/users";
}
}
✅ 主なバリデーションアノテーション:
- @NotNull: nullでないこと
- @NotEmpty: 空でないこと(コレクション用)
- @NotBlank: 空白でないこと(文字列用)
- @Size: 長さ・サイズの範囲指定
- @Min/@Max: 数値の最小/最大値
- @Email: Eメール形式
- @Pattern: 正規表現パターンに一致