ページの作成
親となるページを選択してください。
親ページに紐づくページを子ページといいます。
例: 親=スポーツ, 子1=サッカー, 子2=野球
子ページを親ページとして更に子ページを作成することも可能です。
例: 親=サッカー, 子=サッカーのルール
親ページはいつでも変更することが可能なのでとりあえず作ってみましょう!
| この記事の要点 |
|
Spring エラーの全体像
Spring のエラーは大きく以下に分類できます:
- 起動時 (Bean 生成): BeanCreationException、NoSuchBeanDefinitionException、循環依存
- リクエスト処理時: HttpMessageNotReadableException、MethodArgumentNotValidException
- セキュリティ: AccessDeniedException、AuthenticationException
- データアクセス: DataIntegrityViolationException、LazyInitializationException
- 設定: ConfigurationPropertiesBindException、UnsatisfiedDependencyException
1. BeanCreationException / UnsatisfiedDependencyException
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'userService':
Unsatisfied dependency expressed through constructor parameter 0:
No qualifying bean of type 'com.example.UserRepository' available
原因: 依存する Bean が DI コンテナに存在しない。
// ❌ UserRepository に @Repository / @Component が無い
public interface UserRepository extends JpaRepository { ... }
// ✅ Spring Data JPA なら自動検出されるが、@EnableJpaRepositories のスキャン範囲を確認
@SpringBootApplication
@EnableJpaRepositories(basePackages = "com.example.repository") // 明示
public class App { ... }
// ❌ コンストラクタ注入で型が間違っている
@Service
public class UserService {
public UserService(UserRepository repo) { ... } // UserRepository が DI 対象になっているか
}
2. NoSuchBeanDefinitionException
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'com.example.MyService' available:
expected at least 1 bean which qualifies as autowire candidate
対処:
@Service/@Component/@Repositoryアノテーションが付いているか- コンポーネントスキャンの対象パッケージか (
@SpringBootApplicationのパッケージとサブ) @Configuration+@Beanでの明示登録なら戻り値型が期待型と一致しているか
3. BeanCurrentlyInCreationException (循環依存)
BeanCurrentlyInCreationException: Error creating bean with name 'a':
Requested bean is currently in creation: Is there an unresolvable circular reference?// ❌ A と B がコンストラクタで相互依存 → 起動失敗
@Service class A { public A(B b) {} }
@Service class B { public B(A a) {} }
// ✅ 対処1: @Lazy で遅延注入
@Service class A {
public A(@Lazy B b) { this.b = b; }
}
// ✅ 対処2: setter 注入に変更
@Service class A {
private B b;
@Autowired public void setB(B b) { this.b = b; }
}
// ✅ 対処3: そもそも設計を見直す (中間サービスを抽出)
Spring Boot 2.6+ では循環依存がデフォルトで禁止されます。許可する場合は spring.main.allow-circular-references=true を設定しますが、根本的な設計修正を推奨。
4. NoUniqueBeanDefinitionException
NoUniqueBeanDefinitionException: No qualifying bean of type
'com.example.PaymentService' available: expected single matching bean
but found 2: stripePaymentService, paypalPaymentService// ❌ 同じ型の Bean が複数 → どれを注入すべきか分からない
@Service class StripePaymentService implements PaymentService { ... }
@Service class PaypalPaymentService implements PaymentService { ... }
@Service
public class OrderService {
public OrderService(PaymentService p) { ... } // どっち?
}
// ✅ 対処1: @Qualifier で指定
public OrderService(@Qualifier("stripePaymentService") PaymentService p) { ... }
// ✅ 対処2: @Primary で優先順位を付ける
@Service @Primary
class StripePaymentService implements PaymentService { ... }
// ✅ 対処3: List で全部取る
public OrderService(List services) { ... }
5. HttpMessageNotReadableException
HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type
`java.time.LocalDate` from String "2026/05/17": Failed to deserialize
JSON のフォーマット不正・型不一致。
// ✅ 対処: @JsonFormat で受信フォーマット指定
public class Request {
@JsonFormat(pattern = "yyyy/MM/dd")
private LocalDate birthDate;
}
// グローバル設定
@Configuration
public class JacksonConfig {
@Bean public Jackson2ObjectMapperBuilderCustomizer customize() {
return b -> b.simpleDateFormat("yyyy/MM/dd");
}
}
6. MethodArgumentNotValidException / BindException
// @Valid で起きるバリデーションエラー
@PostMapping("/users")
public User create(@RequestBody @Valid UserDto dto) { ... }
// グローバルハンドリング
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity> handleValidation(MethodArgumentNotValidException e) {
Map errors = new HashMap<>();
e.getBindingResult().getFieldErrors().forEach(err ->
errors.put(err.getField(), err.getDefaultMessage())
);
return ResponseEntity.badRequest().body(errors);
}
}
7. AccessDeniedException (Spring Security)
org.springframework.security.access.AccessDeniedException: Access is denied
原因: 認可エラー。@PreAuthorize や SecurityFilterChain の設定でアクセス拒否。
// ✅ ハンドラー
@ControllerAdvice
public class SecurityExceptionHandler {
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity> handle(AccessDeniedException e) {
return ResponseEntity.status(403).body(Map.of("error", "Forbidden"));
}
}
8. ConfigurationPropertiesBindException
Failed to bind properties under 'app.timeout' to java.time.Duration:
Reason: failed to convert java.lang.String to java.time.Duration# ❌ application.yml
app:
timeout: 30
# ✅ Duration 形式
app:
timeout: 30s # または PT30S
9. LazyInitializationException (Hibernate)
org.hibernate.LazyInitializationException:
could not initialize proxy [com.example.Order#1] - no Session
原因: Entity の Lazy 関連を、トランザクション外(Controller やテンプレート)で参照した。
// ❌ Service で取得した User の orders を Controller で参照 → 例外
@Transactional(readOnly = true)
public User findUser(Long id) {
return userRepo.findById(id).orElseThrow();
}
// Controller では Transaction が閉じている → user.getOrders() で爆発
// ✅ 対処1: JOIN FETCH
@Query("SELECT u FROM User u JOIN FETCH u.orders WHERE u.id = :id")
User findUserWithOrders(Long id);
// ✅ 対処2: @EntityGraph
@EntityGraph(attributePaths = "orders")
Optional findById(Long id);
// ✅ 対処3: DTO に詰めて返す (推奨)
public UserDto findUser(Long id) {
User u = userRepo.findById(id).orElseThrow();
return new UserDto(u.getId(), u.getName(), u.getOrders().stream()...);
}
10. ClassNotFoundException / 起動失敗
Caused by: java.lang.ClassNotFoundException: javax.servlet.Filter
Spring Boot 3.x で javax.* → jakarta.* に変わったため、古いライブラリが原因のことが多いです。依存ライブラリを Spring Boot 3 対応版に更新します。
FAQ
Q: スタックトレースが長すぎて読めない
A: 下から読むのがコツ。 Caused by: 連鎖の最深部に真の原因があります。Spring 起動ログには「Action:」セクションで対処策が書かれていることも多いです。
Q: @Autowired と コンストラクタ注入、どちらを使う?
A: コンストラクタ注入を推奨。final にできて不変・テスタブル・循環依存を早期検知。Lombok @RequiredArgsConstructor で簡潔に書けます。
Q: 開発時に詳細ログを出したい
A: application.yml に logging.level.org.springframework=DEBUG を追加。Auto Configuration の決定理由も --debug オプションで見られます。
ページの作成
親となるページを選択してください。
親ページに紐づくページを子ページといいます。
例: 親=スポーツ, 子1=サッカー, 子2=野球
子ページを親ページとして更に子ページを作成することも可能です。
例: 親=サッカー, 子=サッカーのルール
親ページはいつでも変更することが可能なのでとりあえず作ってみましょう!
- java.lang.IllegalStateException: CGLIB is required to process @Configuration classes
- Error creating bean with name 'org.springframework.aop.config.internalAutoProxyCreator': Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator
- No mapping found for HTTP request with URI ... in DispatcherServlet with name ...
- An internal error occurred during: "Building UI model". com/google/common/base/Function
- No identifier specified for entity : ...
- org.hibernate.hql.internal.ast.QuerySyntaxException: table_name is not mapped
- No compiler is provided in this environment
- java.sql.SQLException: The server time zone value ' ... ' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone
- Caused by: java.lang.RuntimeException: Executing an update/delete query
- Not supported for DML operations
- Field ... required a bean of type ... hat could not be found.
- Annotation-specified bean name ' ... ' for bean class [ ... ] conflicts with existing, non-compatible bean definition of same name and class [...]
- Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback.
- Exception in thread "main" java.lang.UnsupportedClassVersionError
- インストール(eclipseプラグイン)
- クイックスタート
- プロジェクトの作成
- Spring Bootプロジェクトの作成
- Spring Bootプロジェクトの実行
- Spring BootでHello World!
- アノテーション一覧
- DB接続設定からエンティティおよびリポジトリの作成、値の取得まで(JPA編)
- DB接続設定や値の取得(JdbcTemplate編)
- ビューから値をモデルに格納しコントローラーで受け取る方法
- コントローラーにてモデルに値を格納してビューに渡す方法
- テンプレートエンジン
- ModelとModelAndViewの違い
- AOPの使用方法
- classpath: 内部ファイルの読み込み
- file: 外部ファイルの読み込み
- CSVファイルアップロード方法(Ajax)
- CSVファイルダウンロード方法(Ajax)
- Spring Bootプロジェクトのビルドと本番環境へのデプロイ方法(内部tomcat使用)
- Application.propertiesの環境依存設定の分割方法
- JPAにおけるEntityManagerの取得方法
- JPAにおけるjava.sql.Connectionの取得方法
- エラー一覧
- jarの引数を受け取る方法
- Spring BootでGmailからメール送信
- 複数のDBに接続する設定(Spring Boot & JPA編)
- ポート番号の変更
- Basic認証の実装と特定のURLに限定する方法
- Spring SecurityのBasic認証の無効化
- 独自のエラーページを定義する方法
- プロパティファイルの値やjar実行時の引数を取得する方法
人気ページ
- 1 Eclipseで「サーバーに追加または除去できるリソースがありません。」の原因と対処法
- 2 tomcat の起動 / 停止ログと catalina.log・catalina.out の違い
- 3 JavaScript base URL 取得方法|window.location.origin と SSR/Node.js 対応
- 4 YouTube Data API v3 エラー一覧|403/400/404 の主要原因と切り分け
- 5 Spring Frameworkのアノテーション一覧
- 6 Laravel エラー一覧|500/Blade/DB 接続/ルーティングの代表エラー
- 7 3Dグラフィックスとは|モデリング/レンダリング/主要ソフトウェア (Blender / Maya)
- 8 【Spring】@Valueアノテーションとは
- 9 CATALINA_HOME の確認方法 (Linux / Mac)
- 10 【Spring】@Autowiredアノテーションとは
最近更新/作成されたページ
- Laravel キャッシュクリア完全ガイド(cache:clear / config:clear / 2026-05-18 07:42:07
- プロジェクトの作成と削除 2026-05-18 07:42:07
- インストール直後にNetbeansが反応しない 2026-05-18 07:42:07
- 動画やチャンネルの検索 2026-05-18 07:42:07
- APIキー取得方法 2026-05-18 07:42:07
- チャンネル情報の取得 2026-05-18 07:42:07
- API 入門 — Web API(REST / GraphQL / gRPC / 2026-05-18 07:42:07
- インストール(eclipseプラグイン) 2026-05-18 07:42:07
- Laravel「Dotenv values containing spaces must be surrounded 2026-05-18 07:42:07
- エラー一覧 2026-05-18 07:42:07
- curl: (51) SSL: certificate subject name '~' does not match 2026-05-18 07:42:07
- インストール方法(Windows版) 2026-05-18 07:42:07
- JSONから配列に変換 2026-05-18 07:42:07
- 処理を一定時間待つ 2026-05-18 07:42:07
- A non well formed numeric value encountered 2026-05-18 07:42:07
コメントを削除してもよろしいでしょうか?