Error rescue
Paste it and act: 55 real signatures, each answering three things — why it happens, what to do first, which lesson covers it
mvn 不是内部或外部命令mvn is not a command
Maven’s bin folder is not on PATH, or only the Maven bundled inside IDEA exists.
Fix: Add <maven>/bin to PATH, or use the project’s mvnw wrapper. Verify with mvn -v.
Lesson →JAVA_HOME not definedJAVA_HOME missing or wrong
JAVA_HOME must point at the JDK root, not its bin folder and not a bare JRE.
Fix: Set JAVA_HOME to the JDK root, reopen the terminal on Windows, verify with java -version.
Lesson →Unsupported class file major versionClass file version too new
The class was compiled by a newer JDK (61 = 17) but is running on an older JVM (55 = 11).
Fix: Align them: upgrade the runtime JDK, or lower <java.version> in the pom and rebuild.
Lesson →cannot find symbolCannot find symbol at compile time
Usually a missing import, a wrong package name or an unresolved dependency; occasionally the folder is not marked as a source root.
Fix: Read the first line for the class name, confirm the dependency exists in the pom, run mvn -U, and mark the folder as Sources Root.
Lesson →Could not resolve dependenciesDependency cannot be resolved
The coordinates do not exist in the configured repositories: wrong groupId/artifactId/version, a lagging mirror, or a missing private repo in settings.xml.
Fix: Verify the coordinates really exist, delete the failed directory under ~/.m2, rerun with mvn -U, and configure mirror/server credentials for a private repo.
Lesson →duplicate classSame class shipped in two jars
Two coordinates in the tree contain the same class (classic: javax.* vs jakarta.*, or commons-logging pulled twice).
Fix: Run mvn dependency:tree -Dverbose, exclude one side explicitly instead of trusting class-loading order.
Lesson →NoSuchBeanDefinitionExceptionThe container has no such bean
The class is not scanned (outside the base package or missing @Service), a @Qualifier name is wrong, or that bean’s conditional registration did not pass.
Fix: Read the missing type’s full name, confirm the package is scanned, then check the condition report or /actuator/beans to see whether it was registered at all.
Lesson →BeanCurrentlyInCreationExceptionA cycle the caches cannot break
Constructor-injection cycles and prototype-to-prototype cycles are outside what the three-level singleton caches can resolve; Boot 2.6+ forbids them by default.
Fix: Refactor the cycle away first. Otherwise switch one side to setter or @Lazy injection; spring.main.allow-circular-references=true is painkillers, not a cure.
Lesson →NoUniqueBeanDefinitionExceptionSeveral candidates for one injection point
Two implementations of the interface are both in the container and the injection point does not say which one.
Fix: Add @Qualifier("beanName") at the injection point or @Primary on the default; if you rely on @ConditionalOnMissingBean, check evaluation order.
Lesson →BeanCreationExceptionBean creation failed (outermost wrapper)
This line does not carry the root cause — it is the third Caused by below: a throwing constructor, a @PostConstruct failure or binding error.
Fix: Read from the bottom up and fix the last Caused by; the wrapper disappears on its own.
Lesson →Could not resolve placeholderA ${} placeholder could not be resolved
The key is missing and the placeholder has no default, or the profile holding it was never activated.
Fix: Supply the value or write a default (${server.port:8080}); check the active profile printed on the first startup lines.
Lesson →java.lang.ClassCastException: com.sun.proxyProxy type does not match the injected type
A JDK proxy only implements interfaces, but you inject the concrete class — or proxyTargetClass conflicts with the field type.
Fix: Inject the interface (preferred), or set spring.aop.proxy-target-class=true to force CGLIB subclass proxies.
Lesson →aspect is not appliedThe aspect never fires
The pointcut did not match (execution is strict about return type, package and parameter list), or the target bean was never proxied because of self-invocation.
Fix: Prove the match with a loose execution(* com.example..service.*.*(..)) first, then tighten; see the proxy lesson for self-invocation.
Lesson →Port 8080 was already in usePort already in use
Something else owns 8080 — usually a previous java process that did not exit, or Tomcat/Nginx.
Fix: The failure banner names the PID: netstat -ano | findstr 8080 then taskkill /pid on Windows, lsof -i:8080 elsewhere, or pass --server.port=8081.
Lesson →Failed to configure a DataSourceA DataSource was required but never configured
Auto-config sees a DataSource is needed, spring.datasource.url is absent and no embedded database is on the classpath, so startup aborts.
Fix: Provide url/username/password plus the driver, or exclude DataSourceAutoConfiguration when you do not want a database.
Lesson →APPLICATION FAILED TO STARTStartup aborted with a diagnostic banner
Boot’s failure analyser writes the actual reason in that banner — a missing bean, a cycle or a port clash — with the raw stack below it.
Fix: Read the banner first: Description tells you what to change, Action tells you how. Do not start scrolling hundreds of stack lines.
Lesson →while scanning a simple keyInvalid YAML indentation
YAML builds structure from spaces: a Tab, a missing space after a colon, or mixed indentation widths all blow up here.
Fix: Use two spaces consistently, always a space after the colon, and quote values that contain colons.
Lesson →HttpMessageNotReadableException@RequestBody got nothing parseable
The client sent no body, omitted Content-Type: application/json, or the JSON shape does not match the DTO (missing/extra fields, numbers as strings).
Fix: Send Content-Type: application/json, read the offending field name in the message, then fix the DTO or use @JsonIgnoreProperties.
Lesson →MethodArgumentNotValidExceptionValidation rejected the request with 400
@Valid did its job and the payload violates a constraint — good news, dirty data never reached the business layer.
Fix: The body lists objectName and fieldErrors; add @ExceptionHandler(MethodArgumentNotValidException.class) to turn them into field + human message.
Lesson →Failed to convert value of typeA request parameter could not be converted
URL values always arrive as String; a Long or LocalDate target has no matching converter, or the format does not match (2024/01/05 vs yyyy-MM-dd).
Fix: Use @DateTimeFormat(iso = DATE) for dates, wrapper types plus validation for numbers, and register a Converter for global formats.
Lesson →Request method 'POST' is not supported405: verb does not match the mapping
The handler is @GetMapping while the client posts (or @RequestMapping without a method attribute accepts everything).
Fix: Align the verb, and check the mapping table printed by RequestMappingHandlerMapping at startup.
Lesson →HttpMediaTypeNotAcceptableException406: the requested media type cannot be produced
Accept does not match any converter — usually a returned object with no JSON converter, or suffix negotiation reading .pdf as an extension.
Fix: Declare produces = application/json, confirm spring-boot-starter-web (Jackson) is present; suffix negotiation is off by default in Boot 3.
Lesson →MissingServletRequestParameterExceptionA required parameter is absent
@RequestParam defaults to required=true, so a renamed key or a body-only request trips it.
Fix: Send the parameter, or make it optional explicitly with required=false and a defaultValue.
Lesson →Invalid CORS requestThe browser blocked a cross-origin call
The OPTIONS preflight got no matching Access-Control-Allow-* headers — many “403 from my API” cases never reached the handler method.
Fix: Configure @CrossOrigin or a CorsConfigurationSource (allowCredentials cannot combine with allowedOrigins=*), and let OPTIONS through the chain.
Lesson →SQLSyntaxErrorExceptionThe SQL statement itself is wrong
Misspelled table/column, a keyword used as an identifier, or named placeholders (:name) where JDBC only accepts ?.
Fix: Copy the exact SQL from the log into a database client — the fastest honest check there is.
Lesson →DataIntegrityViolationExceptionA database constraint rejected the write
Unique-key clash, a null into a NOT NULL column, or a foreign key pointing at a missing row — Spring already translated the vendor code.
Fix: Use upsert or check-before-insert for unique clashes, reject bad input at validation, and insert parents before children.
Lesson →EmptyResultDataAccessExceptionqueryForObject found zero or many rows
Its contract is “exactly one row”: zero raises EmptyResultDataAccessException, more than one raises IncorrectResultSizeDataAccessException.
Fix: Return a list and decide on empty yourself, or tighten the predicate so uniqueness actually holds.
Lesson →Connection is not available, request timed out afterNo connection available from the pool
The pool is exhausted: uncommitted long transactions, slow SQL, or nested data-source use inside a transaction; it throws after the 30s wait.
Fix: Look for remote calls or loops inside @Transactional, then set leakDetectionThreshold=60000 so Hikari names the borrower.
Lesson →CommunicationsException: Communications link failureThe server closed the connection on its own
A pooled connection outlived MySQL’s wait_timeout, so you borrowed a dead socket; network blips and SSL mismatches look identical.
Fix: Keep max-lifetime clearly below wait_timeout (1740000 vs 28800), enable keepaliveTime if needed, and never ship test-environment timeouts.
Lesson →Invalid bound statement (not found)No SQL bound to the Mapper method
Namespace does not equal the interface FQN, the id differs from the method name, or the XML never reached the classpath (Maven skips XML under src/main/java by default).
Fix: Check target/classes for the XML first, then match namespace and id character by character, then add the resources include rule.
Lesson →LazyInitializationExceptionA lazy load fired after the session closed
The persistence context is gone, so touching an unfetched association can only fail — typical when entities escape to the controller layer.
Fix: Fetch in the transaction with a join or @EntityGraph, or map to a DTO; open-in-view=never is the more honest default.
Lesson →Schema-validation: missing columnddl-auto=validate found entity/schema drift
The entity declares a column the database does not have (or a different name). validate never changes the schema, it only reports.
Fix: Add a Flyway/Liquibase migration, keep validate; never let update alter a production schema.
Lesson →ObjectOptimisticLockingFailureExceptionOptimistic lock conflict on the same row
The @Version you hold no longer matches the row — another transaction committed. That is proof a lost update was prevented.
Fix: Reload, merge and retry, or surface “please refresh”. Do not delete @Version to silence it.
Lesson →Transactional 不生效@Transactional did nothing
Usually one of three: self-invocation bypasses the proxy, the method is not public, or a checked exception was swallowed (default rollback is RuntimeException only).
Fix: Route the call through the proxy, mark rollbackFor = Exception.class, and rethrow instead of swallowing.
Lesson →No qualifying bean of typeNo transaction manager bean
Nothing on the classpath can auto-configure one (no jdbc/jpa starter and no manual @Bean), or several data sources exist without a @Primary.
Fix: Confirm the starter is present, or declare @Primary / an explicit DataSourceTransactionManager bean.
Lesson →@Cacheable 没有缓存效果@Cacheable still hits the database
No @EnableCaching or CacheManager, self-invocation bypassing the proxy, or a key that changes every call (new Date() as argument).
Fix: Check the CacheManager in the startup log, move the method behind another bean, and pin key = "#id".
Lesson →RedisConnectionException: Unable to connectCannot reach Redis
Wrong host/port/password, or Redis binds to 127.0.0.1 with protected-mode and no bind setting; in the cloud a security group blocking 6379 is the usual answer.
Fix: Prove connectivity with redis-cli -h HOST -p 6379 -a PASS first, then fix app config; note Boot 3 uses spring.data.redis.*.
Lesson →SerializationExceptionThe cached value could not be serialized
Jackson needs a no-arg constructor and readable fields, and chokes on inner classes or Java time types unless configured.
Fix: Register JavaTimeModule on GenericJackson2JsonRedisSerializer, or cache a dedicated DTO instead of the domain object.
Lesson →Failed to load ApplicationContextThe test context never started
Test configuration lacks what the main one has (data source, profile, a conditional bean), or the @MockBean/@MockitoBean rename in Boot 3.4 bites.
Fix: Read the first Caused by below it — same path as a production startup failure — then add application-test.yml and @ActiveProfiles.
Lesson →UnnecessaryStubbingExceptionA stub does not match what actually ran
The stubbed method was never called, the arguments differ (Mockito matches strictly by default), or the verification count is wrong.
Fix: Suspect the production path first. Use lenient() only in shared setup, and prefer concrete arguments over anyX().
Lesson →SLF4J: Failed to load classConflicting SLF4J bindings
More than one implementation is on the classpath — typically starter-logging and starter-log4j2 living together.
Fix: Keep exactly one: find the extra implementation with dependency:tree and exclude the starter that drags it in.
Lesson →没有日志输出Log statements produce no output
The level filters it out (DEBUG under root=INFO), the logger name does not match your package, or logback.xml wired no appender.
Fix: Raise the level for your package temporarily and check that the logger name matches the class package.
Lesson →no main manifest attributeThe jar cannot be run with java -jar
It was never repackaged by spring-boot-maven-plugin, so the manifest has no Main-Class and there is no BOOT-INF layout.
Fix: Add the plugin bound to the package phase, rebuild, then java -jar again.
Lesson →ClassNotFoundExceptionA class exists at compile time but not at runtime
BOOT-INF/lib was not read by LaunchedClassLoader (the jar got re-compressed or corrupted), or the dependency was scoped provided/test and never packaged.
Fix: Inspect with jar tf, check the scope, and never re-zip a Spring Boot fat jar with generic tooling.
Lesson →OOMKilledThe process was killed or the heap blew up
The container has a limit the JVM ignores (hard-coded -Xmx, or heap sized from host memory); growing Metaspace usually means dynamic class generation.
Fix: Use -XX:MaxRAMPercentage=75.0 so the heap follows the container limit, cap Metaspace explicitly, then look for oversized collections.
Lesson →'java' is not a commandThere is no java inside the image
The base image ships no JDK, a JRE-only image was used with a wrong java path, or the multi-stage build forgot to copy the runtime in.
Fix: Use eclipse-temurin:17-jre (or COPY --from the JRE) and verify with docker run --rm IMAGE java -version.
Lesson →401 UnauthorizedEverything broke after adding Security
The default policy requires authentication for every request: 401 means no or bad credentials, 403 means authenticated but insufficient authority — different filters report them.
Fix: Declare explicit rules in authorizeHttpRequests, and set logging.level.org.springframework.security=TRACE to see which rule matched.
Lesson →Invalid CSRF tokenA POST was rejected by CSRF protection
Session-based apps enable CSRF by default; the request carried no X-CSRF-TOKEN header or _csrf parameter.
Fix: Send the token back from a cookie repository, or disable csrf() only for genuinely stateless JWT endpoints.
Lesson →ExpiredJwtExceptionToken verification failed
Expired means the clock passed (or server drift); Signature/Malformed means a key mismatch, a truncated token, or a refresh token used as an access token.
Fix: Share one signing key and algorithm, allow clock skew, refresh on 401, and keep the two token types distinct.
Lesson →RejectedExecutionExceptionThe executor rejected a task
Cores, max threads and queue capacity are exhausted, so the rejection policy fires — the default AbortPolicy throws and looks random.
Fix: Configure the pool from the downstream capacity you actually have, and justify CallerRunsPolicy if you choose it.
Lesson →@Async 异常没被捕获An exception inside @Async vanished
Void-returning async methods route errors to AsyncUncaughtExceptionHandler, whose default just logs a line while the caller believes it succeeded.
Fix: Return CompletableFuture and handle it at the call site, or register a handler that raises an alert.
Lesson →TransactionalEventListener 没有触发The @TransactionalEventListener never ran
It only fires inside a matching transaction phase; publish outside a transaction and AFTER_COMMIT is never reached.
Fix: Verify the publisher runs in a transaction, pick the right phase, and keep a plain @EventListener for the no-transaction path.
Lesson →not present in metadata afterBroker reachable but topic metadata times out
advertised.listeners hands out an address the client cannot reach (the usual container/remote-network case), or auto-creation is off.
Fix: Set advertised.listeners to a client-reachable address; allow auto.create.topics locally but provision topics in production.
Lesson →PRECONDITION_FAILED - inequivalent argRabbit refused the queue declaration
A queue with that name already exists with different durable/type/arguments — Rabbit never mutates an existing queue.
Fix: Rename or delete the stale queue, and centralise declarations so two places cannot declare one name differently.
Lesson →Whitelabel Error PageAn Actuator endpoint returns 404
No actuator starter, or the endpoint is outside the web exposure whitelist (health and info only by default), or you hit the wrong port after isolating management.server.port.
Fix: curl /actuator to read the real _links index, then add the include and test both ports.
Lesson →