Every 2–5-year Spring question — bean lifecycle, scopes, AOP, transactions, Boot auto-configuration, profiles, Actuator, Spring Security and JWT — as one-line answers linked to the full answers.
Published September 25, 2026
This page condenses every question from the 2 to 5 Years course in these areas into a single line: the question, linked to its full answer, and the one-sentence answer you should be able to give instantly. Read down the list and answer each question aloud before reading the line. Wherever you hesitate, follow the link and revise the full answer — interviewers at your level expect these basics to be fluent, and they often open with them before going deeper.
Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions — open the lesson
BeanNameAware, ApplicationContextAware…); Runs BeanPostProcessor.postProcessBeforeInitialization; …ApplicationContext and BeanFactory? — BeanFactory is the basic IoC container. It creates beans lazily on request, and supports DI. ApplicationContext extends it, adding: eager singleton creation (fail fast at startup); automatic registration of BeanPostProcessors and BeanFactoryPostProcessors, which is…BeanFactory, and when ApplicationContext? — Use ApplicationContext in practically every application. Spring Boot always creates one. A bare BeanFactory makes sense only in very constrained environments, or in framework code that needs minimal, lazy bean management.BeanCurrentlyInCreationException ("Is there an unresolvable circular reference?").ApplicationEventPublisher); Inject a lazy proxy: @Lazy on one constructor parameter, or ObjectProvider<B>, resolved when first…@Component and @Service? Are they interchangeable? — @Service is a specialisation of @Component (it's meta-annotated with it), so both register a bean through component scanning, and they're technically interchangeable.JpaRepository and CrudRepository, and when would you use CrudRepository? — The hierarchy is CrudRepository → ListCrudRepository → JpaRepository, with PagingAndSortingRepository alongside.@Qualifier and @Primary? (And again: are @Component and @Service interchangeable?) — @Primary marks the default bean when several beans match a type; @Qualifier("name") at the injection point explicitly chooses one, and it overrides @Primary.@Transactional used? — Put @Transactional on a public method of a Spring bean, usually in the service layer. Spring's proxy begins a transaction before the method, commits if it returns normally, and rolls back on RuntimeException or Error.dev, test, prod) that are activated per environment. Beans can carry @Profile, and properties can live in application-{profile}.yml. Activate them with any of: --spring.profiles.active=prod (a command-line…Environment already includes the OS environment variables, so @Value("${DB_PASSWORD}") works. Better still, rely on relaxed binding: the environment variable PAYMENTS_BASE_URL automatically binds to the property payments.base-url, and so to a…Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions — open the lesson
NoUniqueBeanDefinitionException): mark the default with @Primary, or pick one at the injection point with @Qualifier. Or inject a List/Map of all of them, and choose at runtime; Two bean definitions…@ConditionalOnMissingBean. The first one to be evaluated registers the bean, and the others back off.@Spy and @Mock in Mockito? — A @Mock is a complete fake. Every method returns a default (null, 0, an empty collection) unless you stub it, and no real code runs.@Autowired perform? — @Autowired resolves a dependency by type. If several beans match, it narrows the choice using @Qualifier, then @Primary, then the parameter or field name as a fallback.final fields make it immutable, and safe to publish across threads; It's easily testable without Spring: new Service(mockA, mockB); It makes design problems visible: a ten-argument…ApplicationEventPublisher) instead of direct…Spring Boot Internals & Auto-Configuration — Interview Questions — open the lesson
@EnableAutoConfiguration do, and how does auto-configuration work internally? — @EnableAutoConfiguration imports AutoConfigurationImportSelector. At startup, that selector: Reads the candidate classes listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports in every JAR. (Before Boot 2.7, the list was in…@Primary marks the default; @Qualifier("name"), or a custom qualifier annotation, chooses a specific bean; Inject all of them (List<T>, Map<String, T>), and pick dynamically (the strategy pattern); Use ObjectProvider<T> for optional or lazy resolution.ApplicationContext and call getBeanDefinitionNames(), or getBeansOfType(X.class) for one type.SpringApplication creates a ServletWebServerApplicationContext, which obtains a ServletWebServerFactory bean, starts the server, and registers the DispatcherServlet and filters as beans.@SpringBootApplication turns on component scanning from the root package; Auto-configuration supplies the infrastructure beans you'd otherwise declare by hand (the DataSource,…spring init --dependencies=web,data-jpa,actuator --java-version=21 my-service creates a project from Spring Initializr.@SpringBootApplication(exclude = DataSourceAutoConfiguration.class), excludeName = "…" for classes that may not be on the classpath, or the property spring.autoconfigure.exclude=… (which can vary by profile).spring.main.web-application-type=none. The context starts, runs your CommandLineRunners, @Scheduled jobs or message listeners, and the JVM keeps running for as long as non-daemon threads are alive (a Kafka consumer, for example).@SpringBootApplication do internally? — It combines: @SpringBootConfiguration: a @Configuration that Boot's test support can find; @EnableAutoConfiguration: the import selector described above; @ComponentScan, with Boot's TypeExcludeFilter and AutoConfigurationExcludeFilter, so auto-configuration…@ConditionalOnMissingBean. Your configuration is processed before auto-configurations, so by the time the condition is evaluated your bean is already registered.spring-boot-starter-tomcat from the web starter, and add spring-boot-starter-jetty or spring-boot-starter-undertow.@SpringBootApplication; Components: @Component, @Service, @Repository, @Controller/@RestController; Configuration: @Configuration, @Bean, @ConfigurationProperties, @Value, @Profile, @Conditional…; Web: @RequestMapping and its shortcuts,…Spring Boot Configuration, Profiles & Secrets — Interview Questions — open the lesson
.properties, and what are its limitations? — YAML is hierarchical, so it's less repetitive and more readable for nested and list configuration. It supports multi-document files (---), for per-profile sections. Its limitations: It's indentation-sensitive (a misplaced space silently changes the meaning); Implicit typing…application-{profile}.yml files, or sections of a multi-document YAML file guarded by spring.config.activate.on-profile. They override the default application.yml; Beans…spring.config.import=configtree:/run/secrets/) reads Kubernetes secret volumes as properties; Integrations…MessageSource when it finds messages.properties (plus messages_hi.properties, messages_fr.properties…) on the classpath.@ConfigurationProperties, Boot accepts several spellings of the same property name, so the same setting can come from YAML, a system property or an environment variable.application.yml; Put environment overrides in application-dev.yml and application-prod.yml, or better, inject environment values through environment variables; Switch beans with @Profile: a stub payment gateway in dev, and a real one in…AbstractRoutingDataSource, which wraps several target DataSources and chooses one per connection through determineCurrentLookupKey(); Store the routing key in a ThreadLocal context, set by a filter or interceptor from the request (a header, JWT claim or…Spring Boot Data, Transactions & Caching — Interview Questions — open the lesson
@Cacheable, @CachePut, @CacheEvict, @Caching) applied through AOP proxies to bean methods, backed by a pluggable CacheManager. Boot auto-configures the provider it finds: Caffeine: an in-process cache with size, TTL and…spring-boot-starter-cache plus a provider (Caffeine or Redis); Add @EnableCaching; Annotate read methods with @Cacheable; Keep the cache correct with @CacheEvict/@CachePut on writes, plus a TTL as a safety net; …DataSource with a HikariCP pool, EntityManagerFactory, transaction manager and JPA settings, all from spring.datasource.* and spring.jpa.*; Spring Data repositories: CRUD, paging, derived queries (findByStatusAndCreatedAtAfter), @Query,…@Transactional on service-layer methods (the business unit of work), not on controllers or repositories; Keep transactions short. No remote calls, message sends or file I/O inside them. Use the outbox pattern for events that must be consistent with the database change;…Pageable (?page=0&size=20&sort=createdAt,desc), pass it to a Spring Data method, and return the content plus page metadata.deleted flag, or better, a deleted_at timestamp. Intercept deletes, so they become updates, and filter deleted rows out of every query — @Entity @SQLDelete(sql = "UPDATE customer SET deleted_at = now() WHERE id = ? AND version = ?")UserController): HTTP mapping, request and response DTOs, @Valid validation, status codes (201 with Location, 204, 404). No business logic; Service (UserService): business rules (a unique email, password hashing),…Spring Boot Testing, Error Pages & Deployment — Interview Questions — open the lesson
@SpringBootTest with Testcontainers (a real PostgreSQL or…@SpringBootTest and @MockBean used? — @SpringBootTest boots the full application context. Add webEnvironment = RANDOM_PORT to start the real server, for HTTP tests with TestRestTemplate or WebTestClient.@MockitoBean replaces your client bean (for example, PaymentGateway). It's fast, but it skips the HTTP and serialisation code; The HTTP level: WireMock (or MockRestServiceServer for RestTemplate/RestClient) runs a fake…./mvnw spring-boot:build-image. No Dockerfile is needed, and you get layered, reproducible, non-root images with memory-calculator tuning; Jib: builds optimised images without a Docker daemon; A multi-stage Dockerfile using…./mvnw package creates an executable fat JAR with an embedded server. Run it with java -jar app.jar, or containerise it; WAR: set <packaging>war</packaging>, mark the embedded Tomcat starter as provided, and make the main class extend…./mvnw verify), with caching of ~/.m2; Static analysis and security: Checkstyle/Spotless, SonarQube, dependency scanning (OWASP, Snyk), and secret scanning; Integration tests with…BasicErrorController at /error when an error isn't handled and no custom error page exists.OrderNotFoundException), or ResponseStatusException(NOT_FOUND), and map it in @RestControllerAdvice; For unmapped URLs, Spring Framework 6.1+ raises…Spring Boot Performance, Scaling & Resilience — Interview Questions — open the lesson
TimeLimiter; Retries with exponential backoff and jitter, for idempotent operations only;…Spring Boot Async, Events & Messaging — Interview Questions — open the lesson
RestClient (Spring 6.1+, the modern blocking client), Spring Cloud OpenFeign (declarative interfaces), or WebClient in reactive apps. For internal high-throughput calls, gRPC. Always with…@EnableAsync and @Async, a method call is intercepted by a proxy, and executed on a TaskExecutor instead of the caller's thread.@Async correctly? — Add @EnableAsync; Annotate a public method on a Spring bean with @Async; Call it from another bean, because self-invocation bypasses the proxy; Configure a bounded executor; …@Async):; Long-running or important jobs: persist job state in a database table (PENDING/RUNNING/DONE/FAILED, progress, attempts), so it survives restarts and can be queried by users (GET /jobs/{id}). Retry failures with backoff, and alert on stuck or…spring-kafka, and configure spring.kafka.bootstrap-servers, the serializers and a consumer group; Produce with KafkaTemplate.send(topic, key, event), keyed by user ID so each user's messages stay in order; Consume with @KafkaListener, making processing idempotent,…ApplicationEventPublisher.publishEvent(anyObject) (since Spring 4.2, events don't need to extend ApplicationEvent), and handle them with @EventListener, or @TransactionalEventListener (tied to commit…OrderPlaced, PaymentFailed); Publish them where the fact happens; Let each interested module listen, without the publisher knowing who consumes the event.Spring Boot Security Scenarios — Interview Questions — open the lesson
health is exposed over HTTP by default. Add endpoints deliberately (management.endpoints.web.exposure.include=health,info,prometheus); Require authentication and an operations role for everything except health and readiness; Isolate the…@PreAuthorize, including ownership checks ("users can read only their own records"), not just roles; Data minimisation: DTOs per role, and field masking…AttributeConverters and keys held in a KMS), and use row-level security or tenant filters where appropriate. Give the application a least-privilege DB user; Logs: mask PII and secrets in logging (Logback masking patterns), and…Authentication in the SecurityContext.spring-boot-starter-security. Every endpoint is secured by default, with a generated password; Declare a SecurityFilterChain bean that sets the URL rules and the authentication mechanism; Provide users through a UserDetailsService (a database) or an external…RequestRateLimiter (a Redis token bucket), NGINX/Envoy, or an API gateway service; In the application: Bucket4j (a token bucket) in a filter or interceptor. Key it by API key, user or IP. Store the buckets in Redis (or Hazelcast), so the…Origin header (setAllowedOrigins);…Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions — open the lesson
/actuator.java.util.function beans: a Function<I,O>, Supplier<O> or Consumer<I>.lb://service-id for discovery-based load balancing; Security: make the gateway…External APIs, Files, GraphQL & WebFlux — Interview Questions — open the lesson
/api/v1/...) is the most common and operationally simplest. Header or media-type versioning (Accept: application/vnd.shop.v2+json) keeps URLs clean, but is harder to test and cache. Beyond the mechanism: Version…@PostMapping(consumes = MULTIPART_FORM_DATA_VALUE) with a MultipartFile. Validate the size, type (by magic bytes, not just the extension) and name. Stream the content (getInputStream()), never getBytes() for large files. Generate your own storage key; Store:…RateLimiter, or a shared Redis bucket across instances), to stay under each provider's quota; Retries with exponential backoff and jitter, only for…S3Client, or Spring Cloud AWS's S3Template), wrapped in your own FileStorage interface, so the rest of the app doesn't depend on the vendor, and tests can use a fake or LocalStack.spring-boot-starter-webflux (Netty), with controllers that return Mono<T>/Flux<T>, and make the whole chain non-blocking: R2DBC or reactive Mongo/Redis for data; WebClient for outbound HTTP; reactive Kafka if needed.RestTemplate or WebClient? — In new code, use neither by default: RestClient (Spring 6.1+) is the modern synchronous client, with a fluent API; HTTP interface clients (@HttpExchange) give declarative, Feign-like interfaces; WebClient is for reactive or non-blocking applications; RestTemplate…spring-boot-starter-graphql), the official project built on GraphQL Java: Write the schema in src/main/resources/graphql/schema.graphqls; Implement controllers with @QueryMapping, @MutationMapping and @SchemaMapping, reusing your existing…WebClient to get a Flux or Mono, then compose operators: map, filter, flatMap with bounded concurrency, buffer/window for batching, and timeout, retryWhen(Retry.backoff(...)) and onErrorResume for resilience.Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions — open the lesson
spring-boot-starter-oauth2-client): oauth2Login() sends users to an identity provider (Google, Keycloak, Okta) using the authorization-code flow, and obtains tokens.…SecurityContext and SecurityContextHolder? — The SecurityContext holds the current Authentication: the principal, credentials (usually erased after login), and the granted authorities.CookieCsrfTokenRepository), and requires it on state-changing requests (POST, PUT, PATCH, DELETE), as a form field or header.@EnableMethodSecurity, then annotate service methods: @PreAuthorize and @PostAuthorize, with SpEL; @PreFilter and @PostFilter; @Secured and JSR-250's @RolesAllowed, when enabled./admin/), rejects bad tokens early, rate-limits by client, and relays the token downstream (or exchanges it for a…@PreAuthorize/@PostAuthorize can combine authorities, method arguments (#id), return values (returnObject), the authentication object, and custom bean methods (@beanName.method(...)) — `@PreAuthorize("hasAuthority('orders:write') and…SecurityFilterChain, ordered from most specific to most general, and deny by default — @Bean SecurityFilterChain api(HttpSecurity http) throws Exception {Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions — open the lesson
DelegatingFilterProxy → FilterChainProxy, which picks the first matching SecurityFilterChain, and runs its ordered filters. Among them: SecurityContextHolderFilter; CSRF; logout; the authentication filters (form, Basic, bearer token); …ALWAYS, IF_REQUIRED (the default), NEVER, or STATELESS (for token APIs); Session-fixation protection: the session ID changes at login (changeSessionId, the default); Invalid or expired session handling, and timeouts; Concurrency control:…logging.level.org.springframework.security=TRACE. It logs which SecurityFilterChain matched, each filter, and why authorisation failed; Check authentication. Is it a 401 (not authenticated: expired token, missing…AuthorizationManager<RequestAuthorizationContext> for URL rules, or AuthorizationManager<MethodInvocation> for methods, which loads the…spring-security-test, combined with @WebMvcTest or @SpringBootTest: @WithMockUser(roles = "ADMIN"), @WithAnonymousUser and @WithUserDetails, for method or MVC tests; MockMvc request post-processors: .with(jwt().authorities(...)), .with(csrf()),…@PreAuthorize(""" hasRole('TELLER') and #amount <= 50000AuthenticationManager and ProviderManager? — AuthenticationManager is the interface with a single method, authenticate(Authentication), which returns a fully authenticated token or throws AuthenticationException. ProviderManager is its main implementation. It holds a list of AuthenticationProviders, and asks…ExceptionTranslationFilter handlers: For authenticated users without permission, set an AccessDeniedHandler, or simply accessDeniedPage("/access-denied"); For unauthenticated users, set an AuthenticationEntryPoint. It redirects to the login page for web…Q: How should I use this list in the last week before an interview? A: Do one pass per day. Cover the answer text, say your answer out loud, then check it. Mark every question you could not answer crisply, and spend your study time only on the marked ones by opening the linked full answer. By the third pass the marked list should be short.
Q: The interviewer asks one of these basics — should I give only the one-liner? A: Lead with the one-liner, then add one concrete detail or example from your own work. At this level the follow-up usually probes the mechanism behind the basic answer, so be ready to go one layer deeper using the key points in the full lesson.
Q: Some answers here were corrected compared with common prep sheets — why? A: Several widely shared answers are outdated or wrong (for example, Java version details, removed Spring APIs, or SQL queries that miss edge cases). The full lessons call these out under "Common trap" — reading those is the fastest way to stand out from candidates who memorised the same sheets.