Interview
Spring & Spring Boot — Interview Questions (92+)
Conceptual coverage aligned with Spring Framework 6 / Spring Boot 3 (Jakarta EE namespace).
Detailed Questions
1. What is the Spring IoC container?
- Short: Inversion of Control container that creates, wires, and manages beans.
- Detailed:
ApplicationContextloads bean definitions (annotations, Java config, XML), resolves dependencies via DI, manages lifecycle (@PostConstruct,@PreDestroy), and provides AOP, events, resource loading. - Example:
@SpringBootApplicationbootstrapsSpringApplication.run().
2. Dependency Injection types?
- Short: Constructor (preferred), setter, field injection.
- Detailed: Constructor injection makes dependencies explicit, enables
finalfields, easy unit tests without Spring. Field@Autowiredis convenient but hides deps and complicates testing. Spring 4.3+ auto-wires single-constructor beans. - Example:
@Service public class OrderService(OrderRepository repo) {}
3. `@Component` vs `@Service` vs `@Repository` vs `@Controller`?
- Short: Stereotypes — all
@Componentspecializations for semantics and tooling. - Detailed:
@Repositoryadds persistence exception translation.@Controller/@RestControllerfor web.@Servicemarks business layer. Component scan picks all up equally otherwise. - Example:
@RestController=@Controller+@ResponseBody.
4. Bean scopes?
- Short: singleton (default), prototype, request, session, application (web).
- Detailed: Singleton one per container; prototype new per injection/getBean. Request/session need web context. Misuse of prototype inside singleton — client gets one prototype instance unless
ObjectProvideror@Lookup. - Example:
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE).
5. `@Configuration` and `@Bean`?
- Short: Java-based config;
@Beanmethods register objects in context. - Detailed: Full
@Configurationclasses CGLIB-enhanced so@Beanmethod calls return same singleton bean.@Beanlite mode without full config may create new instances per call. - Example:
@Bean DataSource dataSource() { return HikariDataSource... }
6. `@Autowired` resolution?
- Short: By type;
@Qualifieror@Primaryif multiple candidates. - Detailed:
Optionaldependency if zero-or-one.ObjectProvider<T>for lazy/optional multiple. Constructor injection fails fast at startup if missing bean (fail-fast wiring). - Example:
@Qualifier("stripe") PaymentGateway gateway.
7. Spring Boot auto-configuration?
- Short: Conditional beans based on classpath, properties, existing beans.
- Detailed:
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports.@ConditionalOnClass,@ConditionalOnMissingBean. Starters bundle dependencies + auto-config. - Example:
spring-boot-starter-webadds Tomcat, Jackson, MVC.
8. `application.properties` vs `application.yml`?
- Short: Externalized config; YAML hierarchical; profiles
application-dev.yml. - Detailed:
@ConfigurationPropertiesbinds prefix to POJO.@Valuefor single keys. Secrets via env vars / vault, not committed files. - Example:
@ConfigurationProperties(prefix="app.mail") record MailProps(String host, int port) {}
9. Spring MVC request flow?
- Short: DispatcherServlet → HandlerMapping → Controller → View/ResponseBody → ExceptionHandler.
- Detailed: Filters (security) run first.
HandlerAdapterinvokes controller.HttpMessageConverterserializes JSON.@ControllerAdviceglobal exception mapping. - Example:
@GetMapping("/users/{id}") User get(@PathVariable Long id).
10. `@Transactional` how it works?
- Short: AOP proxy wraps bean; begins/commits/rolls back transaction per method.
- Detailed: Self-invocation bypasses proxy (call
this.save()— no tx). Rollback on unchecked by default; checked needrollbackFor. PropagationREQUIRED,REQUIRES_NEW,NESTEDetc. Read-only optimization hint. - Example:
@Transactional(readOnly=true)on query service.
11. Spring Data JPA repository magic?
- Short: Interface extends
JpaRepository; Spring generates implementation at runtime. - Detailed: Query methods parsed from method names (
findByEmailAndActive).@Queryfor JPQL/native. Pagination viaPageable. Custom fragments withImplsuffix. - Example:
Optional<User> findByEmail(String email);
12. Spring Security filter chain?
- Short: Servlet filters authenticate and authorize before reaching controller.
- Detailed:
SecurityFilterChainbean configures HTTP rules, form/login, JWT resource server, CSRF. Method security@PreAuthorizeuses AOP after authentication. - Example:
authorizeHttpRequests(auth -> auth.requestMatchers("/public/**").permitAll()).
Rapid-Fire (Q → A)
- Core Spring modules? → Core, Context, AOP, Data, MVC, Security.
- Bean lifecycle init? → @PostConstruct, InitializingBean, custom init.
- Bean destroy? → @PreDestroy, DisposableBean.
- ApplicationContext vs BeanFactory? → Context superset (events, i18n).
- Component scan base? → @SpringBootApplication scan attribute.
- @Import? → Pull config classes into context.
- @Profile? → Conditional beans on profile.
- active profile property? → spring.profiles.active.
- Actuator endpoints? → health, metrics, env (secure them).
- Starter parent? → Dependency version management.
- spring.factories legacy? → AutoConfiguration.imports in Boot 3.
- DevTools? → Restart, livereload dev only.
- @RestControllerAdvice? → REST exception handler.
- ResponseEntity? → Status + headers + body control.
- @Valid? → Bean Validation trigger.
- @RequestBody? → Deserialize JSON body.
- @ResponseStatus? → HTTP status on method/exception.
- Content negotiation? → Accept header / produces.
- RestTemplate status? → RestClient / WebClient preferred.
- WebClient reactive? → Non-blocking HTTP client.
- @Async? → Separate thread pool execution.
- @Scheduled? → Cron/fixed delay tasks.
- @Cacheable? → Method result caching.
- Cache abstraction? → Redis, Caffeine backends.
- @EventListener? → ApplicationEvent handling.
- ApplicationEventPublisher? → Publish domain events.
- Transaction propagation REQUIRED? → Join or create.
- REQUIRES_NEW? → Suspend and new transaction.
- NESTED? → Savepoint nested (JDBC).
- readOnly true benefit? → Flush optimization, routing replica.
- LazyInitializationException? → Access lazy assoc outside session.
- Open Session In View? → Controversial; keeps session for view.
- EntityManager vs Session? → JPA vs Hibernate native.
- PersistenceContext? → Managed entities scope.
- Detached entity? → No longer tracked.
- merge()? → Reattach detached state.
- flush()? → Sync persistence context to DB.
- clear()? → Detach all entities.
- N+1 problem? → Join fetch or @EntityGraph.
- @EntityGraph? → Specify fetch plan.
- DTO projection? → Interface/class-based Spring Data.
- Specification pattern? → Dynamic JPA queries.
- Criteria API? → Type-safe programmatic queries.
- Querydsl? → Alternative type-safe queries.
- Flyway/Liquibase? → Schema migration with Boot.
- HikariCP default pool? → Spring Boot 2+ default.
- DataSource auto-config? → If JDBC on classpath.
- JdbcTemplate? → Simplified JDBC without ORM.
- RowMapper? → Map ResultSet row to object.
- NamedParameterJdbcTemplate? → Named params :id.
- @Mapper MyBatis? → SQL mapper alternative.
- Spring Test @SpringBootTest? → Full context integration test.
- @WebMvcTest slice? → MVC layer only mock.
- @DataJpaTest slice? → JPA + in-memory DB.
- @MockBean? → Replace bean in test context.
- Testcontainers? → Real DB in Docker tests.
- AOP proxy JDK vs CGLIB? → Interface JDK; class CGLIB.
- @Aspect @Around? → Wrap method proceed().
- Pointcut expression? → execution, @annotation, etc.
- Self-invocation AOP fix? → Inject self or separate bean.
- @Order on filters? → Filter chain ordering.
- CORS config? → WebMvcConfigurer addCorsMappings.
- CSRF REST? → Often disabled for stateless JWT APIs.
- JWT resource server? → oauth2ResourceServer JWT.
- OAuth2 client? → oauth2Client() for login.
- Bean Validation @NotBlank? → String not empty trim.
- @Validated on class? → Method-level validation groups.
- Configuration metadata JSON? → IDE property hints.
- ConditionalOnProperty? → Feature flags.
- Spring Native/AOT? → GraalVM native images constraints.
- Virtual threads Boot 3.2+? → spring.threads.virtual.enabled.
- Observability Micrometer? → Metrics tracing logs.
- @Timed custom metric? → Method timing.
- Structured logging? → JSON log format.
- Graceful shutdown? → server.shutdown=graceful.
- Health groups? → liveness/readiness k8s.
- Property placeholder? → ${app.name} in config.
- @PropertySource? → Additional property files.
- Environment abstraction? → Profiles + property sources.
- FactoryBean? → Complex bean creation.