Troubleshooting Common Issues

1. Resolving Bean Creation Exceptions

Error Fix
NoSuchBeanDefinitionException Add @Component/@Bean; check component scan packages
NoUniqueBeanDefinitionException Use @Qualifier or @Primary
BeanInstantiationException Constructor failure — check root cause
UnsatisfiedDependencyException Missing collaborator bean

2. Fixing Circular Dependency Issues

Example: Fix circular dependency with @Lazy

// Avoid: A → B → A constructor injection (fails by default in Boot 2.6+)
// Fix 1: Refactor — extract shared logic into 3rd bean
// Fix 2: Use setter injection on one side
// Fix 3: @Lazy on the back-edge dependency
public A(@Lazy B b) { this.b = b; }
Warning: spring.main.allow-circular-references=true "fixes" the symptom but masks design problems.

3. Debugging Auto-Configuration Problems

Tool Use
--debug flag Print auto-config report
/actuator/conditions Matched / unmatched conditions
@SpringBootApplication(exclude = {X.class}) Disable specific autoconfig
spring.autoconfigure.exclude Property-based exclusion

4. Resolving Port Already in Use (server.port)

Example: Find port conflict and use random port

# Find process holding the port
lsof -i :8080
# Or use random port
SERVER_PORT=0 java -jar app.jar
# Or assign dynamically
server.port=0  # in application.yml

5. Fixing ClassNotFoundException and NoClassDefFoundError

Cause Fix
Missing dependency Add to pom/gradle
Version conflict mvn dependency:tree + exclusions
Provided/test scope only Change to compile/runtime
Static initializer failed (NoClassDefFoundError after first OK) Check root-cause exception trace

6. Debugging Transaction Not Working Issues

Cause Fix
Self-invocation (proxy bypassed) Call from another bean, or use AspectJ
Method not public Make @Transactional method public
Checked exception Add rollbackFor = Exception.class
Wrong TransactionManager Specify transactionManager = "..."
Non-transactional engine (MyISAM) Use InnoDB

7. Resolving Database Connection Pool Exhaustion

Symptom Action
HikariPool — Connection is not available Investigate leaks & long queries
Set leak detection spring.datasource.hikari.leak-detection-threshold=30000
Increase pool size maximum-pool-size (carefully — DB has limits)
Use read replicas Offload read traffic

8. Fixing CORS Errors in Browser

Example: Global CORS mapping via WebMvcConfigurer

@Configuration
public class CorsConfig implements WebMvcConfigurer {
  @Override public void addCorsMappings(CorsRegistry r) {
    r.addMapping("/api/**")
     .allowedOrigins("https://app.example.com")
     .allowedMethods("GET","POST","PUT","DELETE")
     .allowCredentials(true)
     .maxAge(3600);
  }
}
Note: When using Spring Security, also expose CORS via http.cors(Customizer.withDefaults()).

9. Debugging 404 Not Found Errors

Check Detail
Controller in scanned package Below @SpringBootApplication
Path mapping Match HTTP method + URL exactly
Servlet context path server.servlet.context-path
Static resource handler Files under src/main/resources/static
Trailing slash Spring 6 disabled trailing-slash match by default
logging.level.org.springframework.web=DEBUG See request mapping resolution

10. Resolving Memory Leaks and OutOfMemoryError

Type Diagnosis
Java heap space Heap dump → MAT/VisualVM
Metaspace ClassLoader leak (devtools, hot reload)
Direct buffer Netty/NIO buffers; check -XX:MaxDirectMemorySize
GC overhead limit Heap too small for workload

Example: JVM flags for heap dump on OOM

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/log/heap.hprof

11. Troubleshooting Slow Application Startup

Cause Mitigation
Heavy auto-configuration /actuator/startup to identify slow beans
JPA scanning all entities Restrict basePackages
Eager init of expensive beans spring.main.lazy-initialization=true
Slow DNS Configure name resolution / hostname cache
Large classpath scan AOT processing or native image

12. Fixing LazyInitializationException

Strategy Trade-off
JOIN FETCH in JPQL Best — explicit per query
@EntityGraph Declarative fetch graph
DTO projection Avoid entities outside session
OSIV (Open Session In View) Default ON — antipattern; disable: spring.jpa.open-in-view=false
Warning: Disabling OSIV is recommended, but requires fixing all lazy-loading code paths first.