Top 50 Spring Security Interview Questions and Answers (2026 Edition)
Top 50 Spring Security Interview Questions and Answers (2026 Edition) Work through these 50 questions out loud. Open any question for the full model answer, the trap to avoid, and the follow-up a panel usually asks.
What does Spring Boot do versus what LangChain4j does in the same Java service?
Boot is the host. LangChain4j is how that host talks to models. I keep REST, JWT, and JPA on Spring. I inject ChatLanguageModel from a langchain4j-*-spring-boot-starter and...
How does Spring Boot auto-configuration work?
@SpringBootApplication enables @EnableAutoConfiguration, which loads candidate configs from starters. Each auto-config uses @ConditionalOn* to register beans only when...
Describe the Spring Bean lifecycle.
Container instantiates the bean, injects dependencies, runs BeanPostProcessors, then @PostConstruct or InitializingBean. Singleton lives for context lifetime; prototype creates...
What is the N+1 query problem and how do you fix it?
Loading 100 orders then accessing each order's items triggers 101 queries. Fix with JOIN FETCH in JPQL, @EntityGraph on repository method, or a DTO query selecting only...
What is dependency injection and why does Spring use it?
DI supplies collaborators from outside the class — typically via constructor. Problem solved: tight coupling to concrete classes, hard unit tests, scattered object...
@RestController vs @Controller?
@Controller is for traditional MVC — return "user/list" view name. @RestController adds @ResponseBody so return types become JSON/XML body — standard for REST APIs. Use...
How does @Transactional work?
Spring creates a proxy around @Transactional beans. Calling createOrder() from another bean starts a transaction on the thread-bound EntityManager; commit on success, rollback...
How do you handle exceptions globally in Spring?
Create @RestControllerAdvice with @ExceptionHandler(MethodArgumentNotValidException.class) returning 400 + field map, NotFoundException → 404, generic Exception → 500 without...
Difference between @Component, @Service, @Repository?
All register as singleton beans via component scan. Choose by layer for readability: @Repository on DAOs (plus SQLException translation), @Service on business logic, @Component...
What is the difference between JPA and Hibernate?
JPA is the API contract; Hibernate is the engine under Spring Boot by default. You write @Entity per JPA spec; Hibernate handles SQL generation. Spring Data JpaRepository adds...
Bean scopes in Spring — singleton vs prototype?
Default singleton shares one instance — stateless services. Prototype for per-operation objects. Request/session scopes tie to web lifecycle with proxies. Prototype inside...
How do you test Spring Boot applications?
Unit test services with Mockito — no Spring. @WebMvcTest + MockMvc for controller contract. @DataJpaTest for repository queries. @SpringBootTest + Testcontainers for critical...
How do you version REST APIs?
We use /api/v1/users for clarity. Non-breaking: add optional JSON fields. Breaking: launch v2 path, maintain v1 for 6 months with Deprecation header. Spring maps...
How does spring.config.import work for externalized configuration?
In K8s: spring.config.import=optional:configtree:/etc/secrets/,optional:configtree:/etc/config/ mounts volumes as properties. Vault:...
How do Spring Boot Actuator health probes work with Kubernetes?
Enable probes, configure K8s readinessProbe on /actuator/health/readiness, liveness on /actuator/health/liveness. Custom HealthIndicator for critical deps on readiness group...
What are GraalVM native image considerations for Spring Boot?
Use spring-boot-maven-plugin native profile + GraalVM 21. Run integration tests on native binary. Register reflection for Jackson/custom serializers. Trade longer CI builds for...
How does Bean Validation work in Spring Boot 3?
DTO fields: @NotBlank, @Email, @Size. Controller: createUser(@Valid @RequestBody UserDto dto). Global @RestControllerAdvice maps MethodArgumentNotValidException to 400 + field...
Explain @ConfigurationProperties vs @Value.
@ConfigurationProperties(prefix = "app.payment") record PaymentProps(int timeout, String apiUrl) {} — validated, testable, grouped. Use @Value only for single feature flags....
What is ProblemDetail (RFC 7807) in Spring 6 error handling?
@ExceptionHandler(NotFoundException.class) ProblemDetail handle(NotFoundException ex) { return ProblemDetail.forStatusAndDetail(NOT_FOUND, ex.getMessage()); } — consistent 404...
When should you use spring.main.lazy-initialization?
Use in test slices or large batch apps where most beans unused per run. Production APIs: fix slow @PostConstruct and DB migrations instead. Combine with...
How do you expose custom metrics with Micrometer in Spring Boot?
Service method: orderCounter.increment(); timer.record(() -> process()). Add Tags.of("tenant", tenantId) for multi-tenant. Expose...
How do Spring profiles work for dev, staging, and production?
Base application.yml shared defaults. application-dev.yml local Docker Compose. application-prod.yml from K8s ConfigMap + secrets. Activate via SPRING_PROFILES_ACTIVE=prod....
What is Spring Boot Docker Compose dev services support?
Add compose.yaml with postgres and redis services. Include spring-boot-docker-compose on runtimeOnly. Boot starts Postgres, sets JDBC URL — zero local install. CI uses...
How does Micrometer Tracing replace Spring Cloud Sleuth?
Dependencies: micrometer-tracing-bridge-otel, opentelemetry-exporter-otlp. Traces propagate Authorization-safe headers across RestClient/WebClient calls. Correlate logs with...
What is the difference between @Configuration and @Component?
AppConfig @Configuration with @Bean DataSource — calling dataSource() from another @Bean method returns same instance. Mistake: @Component Config { @Bean Service s() { return...
BeanFactoryPostProcessor vs BeanPostProcessor — explain both.
BFPP: replace ${placeholder} in definitions via PropertySourcesPlaceholderConfigurer. BPP: @Autowired injection, @PostConstruct detection, AOP proxy wrapping. Custom BPP can...
@Primary vs @Qualifier — when to use each?
Two DataSource beans: @Primary mainDataSource for JPA, @Qualifier("analytics") for reporting repo. Prefer @Qualifier when both are equally valid — @Primary for sensible...
ApplicationContext vs BeanFactory — what extra does ApplicationContext provide?
BeanFactory sufficient for minimal DI tests. ApplicationContext adds @EventListener infrastructure, @MessageSource for i18n, Environment integration. Spring Boot creates...
How does Spring Environment resolve property precedence?
Debug with --debug or Environment.getPropertySources(). K8s secret as env var overrides application-prod.yml — intentional for secrets. Document precedence for team. Use...
Explain immutability and why String is immutable.
Immutable objects cannot change after build — thread-safe without synchronization. String immutability allows intern pool, caching hashCode, and security when used as...
Explain JWT authentication flow in Spring Security.
POST /login with credentials → auth provider validates → issue JWT with exp/sub/roles. Subsequent requests include Bearer token. JwtAuthenticationFilter runs before...
What are Spring Boot starters?
spring-boot-starter-web brings spring-webmvc, Tomcat, Jackson with tested versions and enables WebMvcAutoConfiguration. You declare one starter instead of 10 coordinates....
What is CSRF and how does Spring Security handle it?
CSRF tricks logged-in user's browser to POST to your site. Spring stores CsrfToken and validates on mutating requests. For SPA with session cookies, expose token via...
Why is ThreadLocal problematic with virtual threads?
Libraries storing per-request state in ThreadLocal allocate one entry per virtual thread — catastrophic memory with 100k concurrent requests. Prefer ScopedValue for request...
What changed migrating Spring Boot 2 to Spring Boot 3 (Jakarta EE)?
Upgrade to Java 17+, replace imports javax.persistence → jakarta.persistence, update Spring Security config to SecurityFilterChain lambda DSL, run OpenRewrite migration recipe,...
How do you enable virtual threads in Spring Boot 3.2+?
application.yml: spring.threads.virtual.enabled=true on Java 21. Verify integration tests pass — especially security, transactions, MDC logging. Replace custom fixed thread...
springdoc-openapi vs legacy springfox — what should new projects use?
Add springdoc-openapi-starter-webmvc-ui dependency. Annotate with @Operation, @Schema on DTOs. Disable in prod via springdoc.api-docs.enabled=false or secure endpoint. Generate...
How configure Spring Security OAuth2 Resource Server for JWT?
Configure issuer-uri pointing to IdP. SecurityFilterChain: authorizeHttpRequests(auth ->...
Explain OAuth2 Authorization Code flow with PKCE for SPAs.
React app redirects to IdP with code_challenge. Callback with code sent to Spring BFF /oauth/callback — BFF exchanges with code_verifier + client_secret. BFF sets session...
How does @PreAuthorize method security work in Spring Security 6?
@EnableMethodSecurity @Service class with @PreAuthorize hasAuthority order:cancel on cancelOrder(). Use @PostAuthorize for return value checks. Combine with SecurityFilterChain...
Why use BCrypt PasswordEncoder and how to configure it?
@Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(12); } — userService saves encoder.encode(rawPassword). Login: authenticationManager with...
How configure CORS correctly in Spring Security 6?
CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(List.of("https://app.example.com")); config.setAllowedMethods(List.of("GET","POST"));...
SecurityFilterChain vs deprecated WebSecurityConfigurerAdapter?
@Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf(csrf -> csrf.disable()).authorizeHttpRequests(auth ->...
How implement multi-tenancy in Spring Security context?
JWT includes tenant_id — converter sets TenantContextHolder. Base entity @Column tenantId validated on save. Repository methods always include tenant predicate — or Hibernate...
Your API works fine but returns 401 randomly. What could cause this?
Random 401 often means token expiry mid-session, refresh not implemented, or some pods misconfigured with different signing keys. Check JWT `exp`, gateway header stripping, and...
What happens if an exception occurs inside a filter or interceptor?
Exceptions in `Filter` bypass `@ControllerAdvice` unless handled. Filters run before MVC. ```java @Override protected void doFilterInternal(HttpServletRequest req,...
Requests work via curl but fail from frontend. Why?
Browsers enforce CORS; curl does not. Configure allowed origins and methods. ```java @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration c = new...
How do you implement RBAC in React without treating the UI as security?
I ship access.ts with can(user, "interview:question:delete") and wrap dangerous UI in <Can>. Routes use RequirePermission. Spring has the same permission on the controller. On...
Why is storing a JWT in localStorage a problem, and what do you do instead with Spring Security?
I prefer BFF: Vite proxies /api, Spring sets httpOnly cookie, React never sees the JWT. If I must use a bearer token, I keep access token in memory and refresh via cookie. I...
Which JVM and library changes in JDK 15 show up in production ops, not just language trivia?
If we touched 15 on the way to 17/21, I check three ops items: collector is no longer experimental so flags change, ZGC may uncommit so RSS graphs look different, and any...
Spring Security Interview Questions and Answers · Top 40 Spring Security Interview Questions | Must-Prepare before interview. · Spring Security Interview Questions Every Fresher Must Know · Spring Security Interview Questions for 2–3 Years
All interview question lists · Interview guides · Home · Support the platform