Spring/Spring Boot + REST Flashcards

(171 cards)

1
Q

What is Spring Framework?

A

A set of modules for building Java apps (DI/IoC, MVC, AOP, data access, transactions, security). It provides the container that creates and wires objects (beans).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
1
Q

What is Spring Boot?

A

Spring Boot is an opinionated layer on top of Spring that provides auto-configuration, starter dependencies, embedded server setup, and production-ready features (e.g., Actuator) to bootstrap apps quickly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
1
Q

Spring vs Spring Boot (key difference)

A

Spring = core framework and libraries; Boot = auto-configuration + conventions + starters + easier app bootstrapping and packaging.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is IoC (Inversion of Control)?

A

A design principle where the container/framework controls object creation and wiring instead of your code creating dependencies directly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is Dependency Injection (DI)?

A

A pattern where dependencies are provided to a class (via constructor/setter/field) instead of the class instantiating dependencies itself.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Why is DI useful?

A

Testability (easy mocking), loose coupling, easier refactoring, centralized lifecycle management, swapping implementations without changing consumers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a Spring ApplicationContext?

A

The IoC container that holds bean definitions, creates beans, injects dependencies, and manages bean lifecycle.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is a Bean in Spring?

A

An object managed by the Spring container (created, wired, and lifecycle-managed by Spring).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How are beans created in Spring?

A

By component scanning annotations (@Component, @Service, etc.) or by @Bean methods inside @Configuration classes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does @Component do?

A

Marks a class for component scanning so Spring can detect it and register it as a bean.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the purpose of @Service?

A

Semantically marks business/service layer beans. Functionally similar to @Component (but helps readability and tooling).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the purpose of @Repository?

A

Marks persistence layer. Also enables exception translation (converts persistence exceptions into Spring’s DataAccessException hierarchy).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the purpose of @Controller?

A

Marks a web controller (MVC). Typically returns views (not necessarily JSON).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is @RestController?

A

Combination of @Controller + @ResponseBody. Methods return objects serialized as JSON/XML by default (typically JSON).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is @Configuration?

A

Indicates a class contains bean definitions. Spring may proxy it to ensure @Bean methods return singletons consistently.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is @Bean?

A

Defines a bean via a factory method (often used for third-party classes you can’t annotate).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the default bean scope in Spring?

A

Singleton (one instance per application context).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What does singleton scope mean?

A

One shared bean instance per Spring context. Must be thread-safe if used in web apps (multiple requests concurrently).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is prototype scope?

A

A new bean instance is created each time it’s requested/injected.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are request/session scopes?

A

Web scopes. Request = one bean per HTTP request; Session = one bean per HTTP session (web apps).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Why prefer constructor injection?

A

Makes dependencies explicit, supports immutability (final), prevents partially-initialized objects, easier unit testing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Why avoid field injection?

A

Hides dependencies, harder to test, harder to construct without Spring, can complicate immutability and reflection-based issues.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is component scanning?

A

Spring scans packages for stereotype annotations (@Component, @Service, etc.) and automatically registers them as beans.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How does Spring resolve which bean to inject when multiple candidates exist?

A

Using @Primary, @Qualifier, bean name, or by type+name matching.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
What does @Qualifier do?
Selects a specific bean when multiple beans of the same type exist.
24
What does @Primary do?
Marks a bean as the default choice when multiple candidates match a dependency.
25
What is a circular dependency?
Two or more beans depend on each other directly/indirectly, preventing proper initialization (common with field injection).
26
How to fix circular dependencies?
Refactor design, split responsibilities, use constructor injection, introduce interfaces, or restructure bean graph.
27
What is Spring MVC?
The web framework module handling HTTP requests: routing, controllers, argument resolution, validation, and response rendering/serialization.
28
Typical Spring backend layering
Controller (HTTP/API), Service (business logic), Repository (data access). Keeps concerns separated and testable.
29
What should controllers contain?
HTTP concerns: mapping, request parsing, status codes, DTOs, validation triggers. Minimal business logic.
30
What should services contain?
Business rules, orchestration, transactions boundaries, coordination between repositories/clients.
31
What should repositories contain?
DB access logic (JPA repositories, SQL queries, persistence mapping). No business orchestration.
32
What is @RequestMapping used for?
Sets base path and/or HTTP method constraints for controller endpoints.
33
What do @GetMapping/@PostMapping/@PutMapping/@PatchMapping/@DeleteMapping do?
Shortcut annotations to map endpoints to HTTP methods and paths.
34
What is @PathVariable?
Binds a URI template variable to a method parameter (e.g., /users/{id}).
35
What is @RequestParam?
Binds a query parameter to a method parameter (e.g., /users?name=...).
36
What is @RequestBody?
Binds and deserializes the request body (usually JSON) into an object parameter.
37
What is @RequestHeader?
Binds an HTTP header value to a method parameter.
38
What is content negotiation?
Spring chooses response format (JSON/XML) based on request headers (Accept) and configured message converters.
39
What serializes objects to JSON in Spring Boot?
Jackson (commonly). It converts Java objects to JSON and vice versa using ObjectMapper and message converters.
40
What is idempotency?
An operation is idempotent if repeating it multiple times produces the same result as doing it once.
41
Which HTTP methods are typically idempotent?
GET, PUT, DELETE (conceptually). POST is generally not idempotent.
42
Why is GET idempotent?
GET should not change server state; repeated GET requests return the resource representation without side effects.
43
Why is PUT idempotent?
PUT usually replaces/sets a resource to a specific state; repeated calls lead to the same stored state.
44
Why is POST usually not idempotent?
POST often creates new resources; repeated POSTs may create duplicates unless idempotency keys are used.
45
What is an idempotency key?
A client-provided unique key that allows the server to treat retries of a POST as the same operation, preventing duplicates.
46
What are DTOs?
Data Transfer Objects represent API request/response shapes. They protect your domain/persistence model and control serialization.
47
Why avoid exposing JPA entities in controllers?
It couples API to DB schema, risks lazy-loading serialization issues, leaks internal fields, and makes versioning harder.
48
What is a common DTO mapping approach?
Manual mapping, MapStruct, or dedicated mapper classes. Keep mapping consistent and testable.
49
What is Bean Validation?
Standard Java validation via annotations like @NotNull, @NotBlank, @Email, used by Spring with @Valid.
50
What does @Valid do?
Triggers validation on a parameter (often @RequestBody DTO). If validation fails, Spring throws a validation exception.
51
What is MethodArgumentNotValidException?
Exception thrown when @Valid fails on @RequestBody binding/validation.
52
What HTTP status should validation errors return?
400 Bad Request (typically with a structured error payload).
53
What is @RestControllerAdvice?
Global exception handling component for REST. Combines @ControllerAdvice + @ResponseBody.
54
What is @ExceptionHandler?
Defines a method to handle a specific exception type and convert it into an HTTP response.
55
Why centralize error handling?
Consistency, security (don’t leak stack traces), better client experience, easier maintenance.
56
What should a good API error response include?
HTTP status, error code, human-readable message, timestamp, and ideally correlation/trace ID. Avoid sensitive details.
57
Difference between 401 and 403
401 Unauthorized = not authenticated (missing/invalid credentials). 403 Forbidden = authenticated but not allowed.
58
When to return 404?
Resource not found, or to avoid revealing existence of a resource in some security contexts (depending on policy).
59
When to return 409 Conflict?
Conflicting state (e.g., unique constraint violation, version conflict, duplicate resource creation).
60
When to return 500?
Unexpected server error. Should be logged with context; response should be generic.
61
What is @Transactional?
Declares a transactional boundary. Spring manages beginning/commit/rollback of DB transaction for the method execution.
62
Where should @Transactional usually live?
Service layer (business orchestration). Not typically on controllers.
63
Why is @Transactional important?
Ensures atomicity and consistency across multiple DB operations; prevents partial updates.
64
Default rollback behavior in Spring transactions
Rolls back on unchecked exceptions (RuntimeException and Error). Checked exceptions do not rollback by default unless configured.
65
How to rollback on checked exceptions?
Use @Transactional(rollbackFor = SomeCheckedException.class) or wrap checked exceptions into runtime exceptions appropriately.
66
What is transaction propagation?
Defines how a transactional method behaves when called inside another transaction (e.g., REQUIRED, REQUIRES_NEW).
67
What is propagation REQUIRED?
Default. Join existing transaction if present; otherwise start a new one.
68
What is propagation REQUIRES_NEW?
Suspends existing transaction and starts a new one; useful for independent commits like audit logs (careful with consistency).
69
What is self-invocation issue with @Transactional?
Calling a @Transactional method from another method in the same class may bypass the proxy, so transaction may not apply.
70
Why does self-invocation bypass transactions?
Spring applies transactions via proxies/AOP. Internal calls don’t go through the proxy boundary.
71
How to avoid self-invocation transaction pitfalls?
Move transactional method to another bean, call through injected interface/bean, or restructure responsibilities.
72
What is LazyInitializationException?
Common JPA issue when accessing a lazy-loaded relationship outside an active persistence context/transaction.
73
How to reduce LazyInitializationException risk?
Return DTOs (not entities), fetch required relations within transaction, use fetch joins, or tune fetching strategy intentionally.
74
What is the Open Session in View pattern?
Keeps persistence context open for the web request so lazy loading can occur in view/controller. Often discouraged for APIs due to hidden queries and performance surprises.
75
What is Spring Data JPA?
A module providing repository abstractions for JPA: CRUD repos, query derivation, paging/sorting, and custom queries.
76
What is JdbcTemplate?
Spring abstraction over JDBC that simplifies SQL execution and mapping while keeping direct SQL control.
77
When choose JPA vs SQL/JdbcTemplate?
JPA for domain-centric CRUD and relationships; SQL/JdbcTemplate for complex queries, performance-critical paths, or fine control.
78
What are profiles in Spring Boot?
Environment-specific configurations (e.g., dev/staging/prod) selected via spring.profiles.active.
79
Where is Spring Boot config typically stored?
application.yml/application.properties plus profile-specific files like application-dev.yml.
80
Why use externalized configuration?
Separate code from environment settings; easier deployment; safer handling of secrets; consistent environments.
81
How should secrets be handled?
Do not store in repo. Use environment variables, secret managers (AWS Secrets Manager/Parameter Store), or vault solutions.
82
What is @ConfigurationProperties?
Binds structured config properties to a typed class/record, enabling validation and type safety.
83
Why prefer @ConfigurationProperties over @Value everywhere?
Type safety, centralized config, easier testing, less stringly-typed code, supports validation.
84
What is Spring Actuator?
Spring Boot module providing production endpoints (health, metrics, info) for monitoring and ops.
85
Why is /actuator/health useful?
For load balancer readiness/liveness checks and monitoring system health.
86
What are logs vs metrics vs traces?
Logs: events/messages. Metrics: numeric time series (latency, error rate). Traces: request path across services with spans.
87
What is a correlation ID?
A unique identifier attached to a request (often in headers/logs) to track it across services and logs.
88
Why avoid logging PII?
Security/compliance risk and data leakage. Logs often have broad access and long retention.
89
Common Spring Boot startup failure causes
Missing config properties, bean creation exceptions, circular dependencies, classpath conflicts, invalid profiles.
90
Common causes of 500 errors in Spring REST APIs
Null pointer in service, JSON binding errors, DB constraint violations, timeouts to downstream services, unhandled exceptions.
91
What is CORS (high level)?
Browser security mechanism controlling cross-origin requests. Must be configured if frontend and backend are on different origins.
92
What is CSRF (high level)?
Protection against cross-site request forgery, relevant mainly for cookie-based auth. Often disabled for stateless token APIs (carefully).
93
Authorization vs Authentication
Authentication = who you are. Authorization = what you’re allowed to do.
94
What is JWT?
A signed token containing claims (user identity, roles/scopes, expiry). Used for stateless authentication between client and server.
95
JWT important security practices
Validate signature, check expiry (exp), issuer/audience if used, minimize token lifetime, avoid logging tokens, rotate keys.
96
What is method-level security?
Authorization checks on methods (e.g., @PreAuthorize) ensuring only permitted users can execute business operations.
97
What is @PreAuthorize?
Spring Security annotation using SpEL to enforce authorization before method execution.
98
Why enforce authorization in the service layer too?
Defense in depth. Controllers can be bypassed by other entrypoints; service-layer checks protect business rules.
99
What is the “principle of least privilege”?
Grant only the permissions needed to perform a task; reduce blast radius if credentials are compromised.
100
What is pagination and why use it?
Return results in pages to prevent large payloads, reduce DB load, and improve response time.
101
Common pagination parameters
page, size, sort (or cursor-based pagination for large datasets).
102
What is cursor-based pagination?
Uses a stable cursor (e.g., last item ID/timestamp) instead of page numbers; better for large/fast-changing datasets.
103
What is API versioning?
Managing changes in API without breaking clients. Strategies include URL versioning (/v1), headers, or content negotiation.
104
Which API changes are usually backward compatible?
Adding optional fields, adding new endpoints, adding new enum values (careful). Avoid removing/renaming fields.
105
Why are breaking changes risky?
Clients fail unexpectedly. Versioning and deprecation periods help manage changes safely.
106
Good REST status codes for CRUD
Create: 201 Created with Location header. Read: 200 OK. Update: 200 OK or 204 No Content. Delete: 204 No Content.
107
When should you return 204 No Content?
When operation succeeds and you intentionally return no body (common for DELETE).
108
What is a “thin controller”?
A controller that only handles HTTP translation and delegates business logic to services. Improves testability and maintainability.
109
What is a “fat controller” problem?
Business logic in controllers leads to duplication, harder testing, and poor separation of concerns.
110
Testing levels in Spring (overview)
Unit: no Spring context. Slice: partial context (e.g., @WebMvcTest). Integration: full context (@SpringBootTest).
111
What is @WebMvcTest?
Slice test for controllers. Loads MVC components but not full app; typically mocks service layer.
112
When use @SpringBootTest?
Integration testing critical flows and configuration. Slower; use sparingly for high-value paths.
113
How to avoid slow test suites?
Prefer unit tests, use slice tests, limit full context tests, reduce external dependencies (testcontainers only where needed).
114
What should you mock in unit tests?
External dependencies: repositories, clients, time, randomness. Focus on pure business logic behavior.
115
What is contract testing (high level)?
Tests verifying API expectations between services/clients to prevent breaking changes (e.g., consumer-driven contracts).
116
What is a “stable API error contract”?
A consistent error payload structure used across endpoints so clients can handle errors predictably.
117
What is “exception translation” in @Repository?
Spring converts persistence exceptions into unchecked DataAccessException types for consistent handling across technologies.
118
What is AOP in Spring (high level)?
Aspect-Oriented Programming: applies cross-cutting concerns (transactions, security, logging) via proxies around methods.
119
Why do Spring features use proxies?
To intercept method calls and apply behavior before/after (e.g., begin/commit transactions, enforce auth).
120
What is the key implication of proxy-based AOP?
Only calls going through the proxy are intercepted. Internal method calls within the same bean may not be.
121
What are common reasons “works locally but fails in prod”?
Different config/profiles, missing env vars, different DB schema/data, different timeouts, different auth/CORS, dependency differences.
122
How to troubleshoot “works locally but fails in prod” quickly
Check logs and config, confirm active profile, verify secrets and env vars, compare DB schema, reproduce with prod-like settings, add correlation IDs, inspect metrics.
123
What is “service-to-service communication” (basic)?
Backend service calling another service over HTTP/gRPC/messaging. Needs timeouts, retries, and resilience patterns.
124
Why are timeouts essential?
Prevent thread exhaustion and cascading failures; every outbound call should have sensible connect/read timeouts.
125
Why can retries be dangerous?
Can amplify load and cause duplicate side effects. Use retries only for safe/idempotent operations or with idempotency keys.
126
What is a circuit breaker (basic)?
Stops calling an unhealthy dependency temporarily to prevent cascading failure; allows recovery and fallback behavior.
127
What is a bulkhead pattern (basic)?
Isolates resources (threads/pools) so one failing dependency doesn’t take down the entire service.
128
What is a fallback strategy?
Degraded behavior when dependency fails (cached response, default value, queued async processing), while preserving system stability.
129
What is structured logging?
Logging in key-value format (JSON) to enable filtering/aggregation (traceId, userId hashed, endpoint, status, latency).
130
What is an SLI?
Service Level Indicator: a measurable metric (e.g., request success rate, latency).
131
What is an SLO?
Service Level Objective: target for an SLI (e.g., 99.9% success rate, p95 latency < 300ms).
132
How to design a new endpoint (checklist)
Resource naming, method semantics, idempotency, validation, error contract, auth, logging, metrics, pagination/sorting, backward compatibility.
133
What is “defense in depth” in backend services?
Layered security and validation: input validation, auth checks, service-layer authorization, safe defaults, auditing, monitoring.
134
How to prevent SQL injection in Spring apps?
Use prepared statements/parameterized queries (JPA, JdbcTemplate), validate inputs, avoid string concatenation in SQL.
135
How to handle unique constraint violations gracefully?
Catch DB exception, map to 409 Conflict (or 400 depending policy), return stable error code/message.
136
What is “backward-compatible DB migration”?
Deploy changes without breaking old app versions: add nullable column, deploy app that writes both, backfill, then enforce constraints later.
137
Why avoid changing/renaming columns directly?
It can break running versions of the app and cause downtime. Prefer additive migrations and phased changes.
138
What’s a good approach to API documentation?
OpenAPI/Swagger. Keep docs updated, include error models, auth requirements, examples.
139
What’s a good approach to “technical specs” for a feature?
Describe business requirements, API contract, data model changes, sequence flows, tradeoffs, failure modes, and rollout plan.
140
What’s an example of good monitoring for a new endpoint?
Metrics: request count, error rate, latency percentiles. Logs with traceId. Alerts on elevated 5xx or latency.
141
What is a “thin service” vs “rich domain”?
Thin service: mostly orchestrates repos. Rich domain: business rules inside domain objects/value objects. Choose based on complexity; keep invariants protected.
142
Why avoid swallowing exceptions?
It hides failures and breaks observability; prefer either handling with fallback or propagating with context and stable API errors.
143
What is “log and rethrow” pitfall?
Duplicate logs create noise. Prefer logging once at the right boundary with context and then rethrow/wrap.
144
What’s the recommended place to convert exceptions to HTTP responses?
In @RestControllerAdvice (global error handling), not scattered in controllers.
145
How to handle JSON parse errors (bad request body)?
Map to 400 Bad Request with a clear error code (e.g., INVALID_JSON) and safe message.
146
What is “content-type” in HTTP and why it matters?
Content-Type describes request body format (e.g., application/json). Mismatch causes binding errors.
147
What is “Accept” header used for?
Client indicates desired response format. Server uses it for content negotiation (usually JSON).
148
What is “service contract stability”?
Keeping API behavior predictable over time. Avoid breaking changes, keep error formats stable, and use deprecation strategy.
149
What is a good approach to mentoring via code reviews?
Give specific feedback, explain rationale, suggest alternatives, focus on patterns (tests, naming, design), and keep tone constructive.
150
What is a “PR quality checklist” for backend code?
Clear purpose, tests included, validation/errors handled, logging and metrics considered, security checks, backward compatibility, docs updated.
151
What’s a good explanation of Spring Boot auto-configuration?
Boot configures beans based on classpath and properties (conditional configuration), reducing manual setup.
152
What does @SpringBootApplication include?
@Configuration + @EnableAutoConfiguration + @ComponentScan (conceptually). It bootstraps Spring Boot app setup.
153
Why are singleton beans required to be thread-safe?
In web apps, multiple requests execute concurrently and share the same singleton instances.
154
How to design thread-safe Spring services?
Keep services stateless; avoid shared mutable state; use immutable objects; use thread-safe data structures when necessary.
155
What is a “stateless service” in this context?
A service that doesn’t store per-request mutable state in fields; uses method-local variables and dependencies.
156
What are common pitfalls with storing request data in fields?
Data leakage across requests, race conditions, unpredictable behavior under concurrency.
157
What is “ControllerAdvice vs ExceptionHandler in controllers”?
ControllerAdvice centralizes handling across controllers. Local ExceptionHandler affects only one controller; global is usually cleaner.
158
How to return a custom HTTP status in Spring?
Return ResponseEntity with status or use @ResponseStatus on exception classes/handler methods.
159
What is ResponseEntity?
A wrapper that allows controlling HTTP status, headers, and body explicitly from controller/handler methods.
160
When should you use ResponseEntity?
When you need custom status codes, headers (Location), or conditional responses beyond default behavior.
161
What is “Location” header used for?
On creation (201), it points to the URI of the newly created resource.
162
How to handle partial updates?
Use PATCH with clear semantics; validate fields; consider JSON Merge Patch or explicit update DTO.
163
What is optimistic locking (high level)?
Prevents lost updates using a version field; conflicts produce 409. Common in JPA via @Version.
164
Why is optimistic locking useful?
Detects concurrent updates without heavy locking, improves consistency for collaborative edits.
165
What is “service orchestration”?
Coordinating multiple repositories/clients in a single business operation, often inside a transaction and with failure handling.
166
What is “requirements analysis” in backend terms?
Clarifying inputs/outputs, constraints, validation rules, performance targets, security needs, and edge cases before coding.
167
What is a “failure mode” to consider in a feature spec?
DB down, dependency timeout, partial failure, duplicate requests, bad input, inconsistent data, degraded performance.
168
What is “rollout plan” best practice?
Use feature flags, staged deployments, backward-compatible changes, monitoring, and rollback readiness.
169
What is a rollback strategy for deployments?
Revert to previous artifact, disable feature flag, restore DB if needed (prefer forward-fix + backward compatible migrations).