123 Spring & Spring Boot interview questions with detailed answers, sorted from basic to advanced. Free to practice, with progress saved automatically.
Spring is a Java framework for building backend applications around inversion of control, and Spring Boot adds auto-configuration and sensible defaults on top of it. The questions cover dependency injection, core annotations, Spring MVC versus WebFlux, Spring Data JPA and fetching, transactions and rollback rules, security, externalized configuration, testing, Actuator, and microservices.
and 28 more topics.
Spring Boot is a framework for building Java/Spring apps fast, with minimal configuration, built on top of Spring Framework to remove most XML and boilerplate. Three core parts: 1. Auto-configuration — configures the app from the dependencies on the classpath. For example, if Tomcat is…
DI: dependencies are supplied from outside instead of an object new-ing them → less coupling, better testability (mockable in tests). Instead of hardcoding new UserRepository() inside the class, the constructor receives a UserRepository from outside — the class declares what it needs, not how to…
@Autowired enables automatic injection — Spring finds the matching bean in the container and passes it in. Works on constructors, setters, fields. How Spring picks the bean: - By type by default: it looks for a bean of type PaymentGateway. - Several beans of the…
@Component @Bean --------- Placed on Class Method in a @Configuration Bean created Spring calls the constructor and injects its parameters (no @Autowired needed if the class has a single constructor) You new it inside the method and return the object Init control Limited Flexible —…
Externalized config means moving environment-specific values (DB URL, port, log level...) out of the code so you can change them without a rebuild. Spring Boot reads them from application.properties or application.yml, two files with the same content in different formats: (application.properties is the flat form:…
Actuator adds a set of operations endpoints to the app (health, metrics, build info...) over HTTP or JMX, so you do not write monitoring code yourself. Add the spring-boot-starter-actuator starter and it works. By default only the /actuator/health endpoint is exposed over HTTP. The rest…
Spring Data JPA is an abstraction over JPA — declare an interface and Spring generates the implementation. @Repository: marks the data-access component + auto translates DB exceptions (SQLException) → Spring DataAccessException (unchecked, consistent across DBs). JpaRepository includes @Repository implicitly. Benefits: minimal code; a wrong query…
@Transactional — declarative transactions: Spring handles begin → commit → rollback, no manual connection.commit(). Everything in the method runs in one transaction — any step throwing an exception rolls back all of it (e.g. placeOrder = save order → reserve stock → charge payment: if…
readOnly = true tells Spring and Hibernate that this transaction only reads, so they can skip the work meant for writes. It is a hint: it optimizes and blocks writes through Hibernate, but it is not a mechanism that forbids writes at every layer. Effects:…
Mono<T and Flux<T are the two Project Reactor publisher types that Spring WebFlux is built on. Mono emits 0 or 1 item (like an async Optional), Flux emits 0..N items, possibly infinite. Both are lazy: nothing runs until someone calls subscribe. Backpressure lets the receiver…
@SpringBootApplication is a meta-annotation combining the three most-used annotations: Annotation Effect ------ @Configuration Class is a bean definition source @EnableAutoConfiguration Enables auto-configuration @ComponentScan Scans components from the current package downward Usage: place it on the main class (running SpringApplication.run(App.class, args)) at the root package so…
Auto-configuration is the mechanism by which Spring Boot creates beans automatically, based on the libraries on the classpath and the beans your app has already declared. Add spring-boot-starter-web to your dependencies and the app gets Tomcat and a DispatcherServlet without manual setup. An auto-configuration class…
Scope defines the lifecycle and number of instances of a bean. Scope Instances Use when --------- singleton (default) 1 shared across the app Stateless services, repositories prototype New on each inject/getBean Stateful objects (command, builder) request / session 1 per HTTP request / session (Web)…
DevTools is an optional dependency that speeds up development: it restarts the app when code changes and refreshes the browser. Add spring-boot-devtools and mark it <optionaltrue</optional (Maven) or configure it as developmentOnly (Gradle), so it is not pulled into other modules that depend on the…
Bean lifecycle: create the instance (constructor) → inject dependencies (field/setter) → @PostConstruct → bean ready → @PreDestroy (on context close). @PostConstruct — an init method called after DI completes, so every dependency is ready. With field/setter injection, a dependency is still null while the constructor…
@Value @ConfigurationProperties --------- Binding Single property Group of properties in a class Type checking Converts each value on its own; a wrong key or type only shows up when the bean is created Binds the whole group into typed fields, errors reported together at startup…
A profile is an environment label (dev, staging, prod) that Spring uses to decide which configuration to load and which beans to create. That lets you build one JAR once and run it in every environment, changing only the profile at startup. Turn a profile…
Circular dependency: A needs B and B needs A → Spring cannot decide which to create first. Spring Boot 2.6+ throws at startup: The dependencies of some of the beans form a cycle: a → b → a. Fixes (prefer in order): 1. Refactor —…
When there are several beans of the same type, Spring does not know which one to inject and throws NoUniqueBeanDefinitionException at startup. Two ways to name the bean you want: - @Primary — placed on one bean to make it the default when there are…
@Controller @RestController --------- Returns View name (template) Data directly (JSON/XML) Use case Web MVC (Thymeleaf, JSP) REST API @RestController = @Controller + @ResponseBody. - A @Controller method returns a view name — return "home" → the ViewResolver finds templates/home.html and renders HTML. - A @RestController…
Annotation Source Example --------- @PathVariable URI path segment GET /users/42 @RequestParam Query string GET /users?page=2&size=10 @RequestBody Request body (JSON) POST /users - @PathVariable — resource identifier (ID, slug) in the path, required: @GetMapping("/users/{id}") + @PathVariable Long id. - @RequestParam — filter/paging/sort from the query string.…
JPA Hibernate Spring Data JPA ------------ What it is Specification (Jakarta Persistence) Implementation of JPA Abstraction on top of JPA Maintained by Jakarta EE Hibernate (Commonhaus Foundation) Spring - JPA = the standard (interfaces, annotations, JPQL), now officially named Jakarta Persistence (package jakarta.persistence from Spring…
Lazy Eager --------- Loads when First field access Always with the parent entity Default @OneToMany, @ManyToMany @ManyToOne, @OneToOne Change it with the fetch attribute: @ManyToOne(fetch = FetchType.LAZY). Eager problem: it always loads associations even when they are not used, so it runs extra queries and…
N+1 problem: load a list of entities with 1 query, then run one extra query per entity to load its lazy association. The result is 1 + N queries instead of 1. getCustomer() only returns an empty proxy; Hibernate runs the query for the customer…
Authentication: "Who are you?" — verifying identity (password login, JWT, OAuth). Authorization: "What are you allowed to do?" — checking permissions (roles, scopes). Authentication always happens before authorization. In Spring Security: - Authentication: implement UserDetailsService.loadUserByUsername() returning a UserDetails (username, password hash, authorities) — Spring compares…
The Security Filter Chain is the chain of servlet filters Spring Security places before controllers, each handling one job (loading the SecurityContext, authentication, authorization checks...). How it works: the servlet container only knows filters registered the standard Servlet way, while Spring Security's filters are beans.…
JWT (JSON Web Token) = stateless authentication — the server stores no session and verifies via signature. Flow: 1. POST /login → server verifies credentials → signs and returns a JWT. 2. The client sends the header Authorization: Bearer <token on every request. 3. Server…
CSRF (Cross-Site Request Forgery): an attacker tricks the user's browser into sending a request — the browser automatically attaches the session cookie, so the server thinks the request is legitimate. Protection mechanism: the server issues a CSRF token (random, per-session) embedded in forms → every…
@SpringBootTest boots the full ApplicationContext: it loads all beans and auto-configs and connects to a DB as in production. It is usually paired with @AutoConfigureMockMvc to hit endpoints through MockMvc without a real server. A unit test is very different: it creates objects with new,…
Slice tests load only one slice of the ApplicationContext — faster than @SpringBootTest, isolating the layer under test. @WebMvcTest — controller layer: @DataJpaTest — repository layer: By default @DataJpaTest swaps the DataSource for an embedded DB (H2 if it is on the classpath) and wraps…
@Mock (Mockito) @MockBean (Spring Boot) --------- Spring context Not needed Required (replaces bean in context) Use with Pure unit tests Slice tests / @SpringBootTest Speed Fast Slower (invalidates context cache) @Mock — plain Mockito: run with @ExtendWith(MockitoExtension.class), combined with @InjectMocks to place mocks into the…
HealthIndicator adds custom health checks to /actuator/health — important for Kubernetes liveness/readiness probes. Response: /actuator/health → {"status":"DOWN","components":{"externalApi":{"status":"DOWN"}}}. Liveness vs Readiness (K8s): /actuator/health/readiness = DOWN → K8s stops routing traffic to the pod. Note: think carefully before adding an external API to the readiness group. If…
@Async runs a method on a separate thread pool — non-blocking from the caller's perspective. Thread pool config (important): Without your own executor: Spring Boot auto-configures a ThreadPoolTaskExecutor with 8 core threads, tunable via spring.task.execution.pool.. With virtual threads enabled (spring.threads.virtual.enabled=true, Java 21+), Boot uses a…
Spring Cache stores the result of a method so a later call with the same arguments does not have to run it again. You only add annotations; where the data is stored (in-memory Caffeine, Redis...) is decided by the CacheManager and does not affect your…
@ExceptionHandler marks a method that handles one kind of exception. @ControllerAdvice collects those handlers in one class shared by every controller, so you do not scatter try/catch. @RestControllerAdvice is @ControllerAdvice plus @ResponseBody, meaning the return value is written straight to the response body (JSON) instead…
Both trigger Bean Validation on method arguments or fields. @Valid (Jakarta) @Validated (Spring) --------- Validation groups No Yes Cascades into nested objects Yes (on a field) No Method-level validation No Yes (on the class) Basic usage (either works): create(@RequestBody @Valid CreateUserRequest req). The real difference…
Spring Boot reads properties from several sources; a source with higher priority overrides a lower one. The order, from high to low: 1. Command-line args (--server.port=9090) 2. SPRINGAPPLICATIONJSON (JSON in an env var or system property) 3. Java system properties (-Dserver.port=9090) 4. OS env vars…
@ConditionalOnProperty creates a bean only when a property has a specific value — feature flags, optional components. Set app.feature.email: true in config → EmailNotificationService is created; flip to false or remove the line → the no-op bean is created instead, no code change. matchIfMissing =…
The interfaces in the Spring Data hierarchy: Spring Data 3.x: PagingAndSortingRepository no longer extends CrudRepository (unlike 2.x). For both CRUD and paging, extend both, or use JpaRepository, which bundles everything and adds JPA-specific methods. saveAll is already in CrudRepository. What JpaRepository adds are the flush…
Flyway manages schema migrations as versioned SQL files, which gives a clear change history and lets you rebuild the same schema in every environment. Add the flyway-core dependency and Spring Boot integrates it automatically. From Flyway 10 (Spring Boot 3.3 and later), Postgres/MySQL need a…
HikariCP is a JDBC connection pool — keeps a reusable pool of DB connections instead of opening/closing one per request (opening a connection costs tens of ms + handshake). Default in Spring Boot 2+ because: fastest in HikariCP's benchmarks (vs Tomcat CP, DBCP2, C3P0) —…
ResponseEntity<T gives full control over the HTTP response: status code, headers, body. Returning an object directly → Spring defaults to 200 OK. Use ResponseEntity when you need a non-200 status, custom headers, or a possibly-null body.
@Scheduled runs a method on a recurring schedule, for example a cron job or a background task. Enable it with @EnableScheduling on a config class. Spring cron has 6 fields (Unix has 5): {seconds} {minutes} {hours} {day} {month} {day-of-week}. Two things you meet in real…
Three ways to make HTTP calls from a Spring app to external APIs: RestTemplate WebClient RestClient ------------ Model Blocking Non-blocking (reactive) Blocking (fluent) Status Maintenance only; deprecation announced Actively developed Actively developed (Spring 6.1+) API style Template method Fluent builder Fluent builder RestClient (recommended for…
Spring Kafka uses KafkaTemplate to produce and @KafkaListener to consume. Add the spring-kafka dependency and configure it through spring.kafka. (bootstrap-servers, consumer group-id, JSON serializer/deserializer). The message key (order.getId()) decides the partition. Messages with the same key always go to the same partition, so the messages…
Service discovery lets services find each other by logical name instead of a hardcoded IP:port, because instances constantly scale up and down and change IP. Two common approaches: 1. Kubernetes Service (most common) — K8s handles discovery through DNS: just call http://order-service/api/orders, and kube-proxy load-balances…
Sensitive Actuator endpoints (/env, /heapdump, /loggers) must be protected — never public. 3 layers (combinable): 1. Expose only what is needed + separate port: A separate port lets you block it at the network level: on K8s the public Service/Ingress points only at the app's…
@ResponseStatus assigns an HTTP status to an exception class or a controller method — a static declaration instead of ResponseEntity. On an exception class: Spring catches the exception → returns the declared status automatically. On a controller method: vs ResponseEntity: @ResponseStatus for a fixed status,…
Spring Boot 3 (2022) — a major release with breaking changes. Minimum requirements: Java 17 (Boot 2: Java 8), Jakarta EE 10. Biggest change — namespace: every javax. import → jakarta. (e.g. javax.persistence.Entity → jakarta.persistence.Entity, same for validation/servlet; keep javax.sql, javax.xml — not part of…
All are specializations of @Component → all are component-scanned and created as beans. They differ in layer semantics + extra features: Annotation Layer Extra feature --------- @Component Generic None @Service Business logic None @Repository Data access (DAO) Yes — Exception translation @Controller Web (returns view)…
Starters are pre-packaged dependencies — adding one starter pulls in all required libs + the matching auto-config, with no need to manage individual dependencies/versions. Starter Includes ------ spring-boot-starter-web Spring MVC + Tomcat + Jackson spring-boot-starter-data-jpa Spring Data JPA + Hibernate + HikariCP spring-boot-starter-security Spring Security…
Constructor Setter Field ------------ Immutability Yes (final) No No Mandatory dependency Yes, visible in the constructor No, optional by default No Testability Best Good Poor, needs reflection Circular dep Detected early Can be hidden Can be hidden Why constructor injection is best: final → immutable/thread-safe;…
Self-invocation: a method calling another method in the same class → @Transactional is ignored. Spring transactions run through an AOP proxy — the proxy wraps the bean, intercepting external calls to begin/commit. Calling this.B() goes straight to the object, bypassing the proxy → the annotation…
CORS (Cross-Origin Resource Sharing) is a mechanism that uses HTTP headers to let a server allow web pages from another origin to call its API. An origin is the combination of scheme, host and port. By default the browser enforces the same-origin policy: JavaScript running…
Testcontainers is a library that starts real Docker containers (Postgres, Redis, Kafka…) while tests run and stops them afterwards, so integration tests run against the same kind of infra as production instead of H2. Add spring-boot-testcontainers + org.testcontainers:postgresql (test scope). Spring Boot 3.1+ — @ServiceConnection:…
Spring Boot embeds a web server (Tomcat, Jetty; Undertow up to Boot 3.x) into the JAR — deploy as an executable, no separate server install. Default: Tomcat (spring-boot-starter-web). Switch to Jetty: exclude Tomcat from starter-web and add spring-boot-starter-jetty: Tomcat Jetty Undertow ------------ Default Yes No…
Spring Data provides Pageable/PageRequest for pagination and Sort for sorting. A controller can take Pageable directly as a parameter, and Spring reads ?page=0&size=20&sort=createdAt,desc from the query string. Pages are numbered from 0. PagedModel wraps the Page into stable JSON: a content list and a page…
Actuator + Micrometer export metrics to Prometheus → Grafana visualizes them. Add spring-boot-starter-actuator + micrometer-registry-prometheus, then expose: Custom metric: Prometheus periodically calls this endpoint to collect metrics (pull), so you only need to declare a scrape job: - Built-in metrics: JVM memory/GC, Tomcat threads, HikariCP…
SpringDoc OpenAPI reads your controllers and DTOs at runtime and generates API documentation in the OpenAPI 3 format, so you do not write a YAML file by hand. Just add the springdoc-openapi-starter-webmvc-ui dependency and the app exposes two URLs with no configuration: - GET /v3/api-docs:…
BeanFactory and ApplicationContext are both Spring IoC containers — ApplicationContext is the superset. Feature BeanFactory ApplicationContext --------- Lazy loading Yes (default) No, eager (singletons created at startup) AOP, @Transactional No Yes Event publishing No Yes (ApplicationEvent) MessageSource (i18n) No Yes Web context No Yes (WebApplicationContext)…
AOP (Aspect-Oriented Programming) separates work that repeats in many places, called a cross-cutting concern (logging, authorization, timing, opening transactions), from business logic. Instead of copying that code into every method, you write it once and declare which methods it runs around. Concepts: an aspect is…
Both listen to ApplicationEvent, differing in when they run relative to a transaction. - @EventListener — runs immediately on publish, inside the same transaction. If the listener throws → the whole transaction rolls back. - @TransactionalEventListener — runs after the transaction commits successfully. On rollback…
Method-level security protects individual methods with annotations rather than only at the URL level. Enable with @EnableMethodSecurity (replaces the deprecated @EnableGlobalMethodSecurity). @PreAuthorize — checks before the method runs (uses SpEL): An ownership check must compare the order's owner with the current user. orderId == principal.id…
Virtual Threads (Java 21) are very lightweight threads managed by the JVM, not OS threads. Enable them in Spring Boot 3.2+ with one line of config: spring.threads.virtual.enabled: true. Boot then uses them for Tomcat, @Async and @Scheduled. Why it matters: an OS thread costs about…
Spring Boot does not replace Spring Framework — it is a convenience layer built on top of Spring that removes manual configuration. Spring Framework Spring Boot --------- Role Core platform (IoC, DI, AOP, MVC) Convenience layer on Spring Configuration Manual (XML / lots of Java…
Both intercept requests before the controller, but at different layers. Filter (Servlet) HandlerInterceptor (Spring MVC) --------- Layer Servlet container (before DispatcherServlet) Inside DispatcherServlet Knows the handling controller? No (handler not chosen yet) Yes (handler argument) Access to Spring context Limited Full (it is a Spring…
JPA maps Java classes ↔ DB tables via annotations — no manual SQL DDL. - @Entity — the class is a JPA entity (one table); @Table — table name. - @Id — primary key; @GeneratedValue — ID generation (IDENTITY auto-increment is common, SEQUENCE, UUID). -…
The 4 states of an entity relative to the Persistence Context: - Transient (new) — just new-ed, unknown to JPA, no DB row yet. - Managed (persistent) — tracked by the Persistence Context (after persist(), find(), or a query result) → gets dirty checking: mutate…
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping are shortcuts (composed annotations) for @RequestMapping(method = ...), available since Spring 4.3: - @GetMapping("/users") = @RequestMapping(value = "/users", method = RequestMethod.GET). Differences worth remembering: - @RequestMapping can sit at class level as the controller-wide base path; the shortcuts work only…
An Entity = an object mapped to a DB table, managed by JPA. A DTO (Data Transfer Object) = a plain object carrying data across a boundary (API response/request), free of persistence concerns. Why not return entities straight from controllers: 1. Leaks the DB structure…
Config Server centralises configuration for many services — instead of each service keeping its own application.yml, all read from one shared source, usually a Git repo (config becomes versioned, reviewed, audited via commits). Server: the spring-cloud-config-server dependency + @EnableConfigServer, pointing spring.cloud.config.server.git.uri at the config repo.…
An API Gateway = the single entry point of a microservices system — clients call one endpoint and the gateway routes to the right backing service. Its main value: pulling shared concerns into one place — authentication, rate limiting, CORS, logging, retries — instead of…
Spring Boot enables auto-config based on the classpath. To disable a specific one there are 3 ways: 1. The exclude attribute of @SpringBootApplication (which delegates to @EnableAutoConfiguration): 2. @EnableAutoConfiguration(exclude = ...) if you are not using the composed annotation. 3. Via a property — use…
@ComponentScan tells Spring to scan packages for classes marked with a stereotype (@Component, @Service, @Repository, @Controller, @Configuration) and register them as beans. Default base package: the package containing the class that declares the annotation. Since @SpringBootApplication already bundles @ComponentScan, Spring scans from the main class's…
No. By default Spring only marks a transaction for rollback when the method throws a RuntimeException (unchecked) or an Error. A checked exception thrown out of a transactional method still commits. To roll back on a checked exception, declare it explicitly: Conversely, noRollbackFor keeps the…
Use ApplicationRunner or CommandLineRunner. Both have exactly one run(...) method, which is called just before SpringApplication.run(...) completes: at that point the context has finished refreshing and the web server is up. Differences: - CommandLineRunner gets raw String... arguments; ApplicationRunner gets ApplicationArguments with option/non-option already parsed.…
A class annotated with @ConfigurationProperties("prefix") must become a bean before Spring binds it. Three ways: - @EnableConfigurationProperties(MyProperties.class) on a @Configuration class. - @ConfigurationPropertiesScan on the main class (scans the package). - Add @Component to the properties class itself. This only works for the setter style…
Graceful shutdown means that on a stop signal (SIGTERM) the web server stops accepting new requests but lets in-flight requests finish within a grace period before shutting down. Without it, a container killed mid-flight returns errors for requests already in progress — a common problem…
No. Dependencies are resolved once, when the singleton is instantiated: Spring creates exactly one prototype instance, injects it, and the singleton reuses that instance for its whole life. This is a classic trap because the code looks correct at a glance. To get a fresh…
The difference is whether inter-bean calls go through the container. - @Configuration (full mode): Spring generates a CGLIB subclass of the config class. One @Bean method calling another is intercepted and returns the container singleton. - @Bean in a class without @Configuration, or @Configuration(proxyBeanMethods =…
The core Spring AOP rule: - The target implements at least one interface → a JDK dynamic proxy is used, exposing only those interfaces. - The target implements no interface → CGLIB is used, generating a runtime subclass of the class. Force CGLIB with proxyTargetClass…
Because they go through two different mechanisms. 1. @Valid on @RequestBody — validation runs in the Spring MVC argument resolver after JSON deserialization. Failure throws MethodArgumentNotValidException (a BindException), carrying a BindingResult with each FieldError. 2. Constraints directly on parameters (@RequestParam @Min(1) int page) — this…
Through ProblemDetail — an implementation of RFC 9457 (successor to RFC 7807), returning Content-Type: application/problem+json with the standard fields type, title, status, detail, instance plus arbitrary extensions. Two ways to use it: Extend ResponseEntityExceptionHandler in a @ControllerAdvice to inherit handlers for all standard Spring MVC…
Since Spring Boot 2.6, circular references between beans are prohibited by default. Previously the container broke a cycle through fields or setters by injecting a partially initialized bean; now it fails fast at startup. A cycle through constructors could never be resolved, in any version.…
- spring.profiles.active: the list of enabled profiles. Setting it again at a higher-precedence source replaces the list rather than appending. Usually passed at runtime: --spring.profiles.active=prod. - spring.profiles.include: adds profiles on top of the active list, for baseline profiles you always want (e.g. common). Included profiles…
Spring Data JPA offers three ways to declare a query; pick by complexity: 1. Derived query — Spring generates JPQL from the method name. Concise and type-safe, but names grow unwieldy once you add conditions. 2. @Query with JPQL — a hand-written query that still…
It is thrown when you touch a LAZY association after the persistence context has closed: the proxy no longer has an EntityManager to load from. If the service has no @Transactional, the repository's transaction ends as soon as findById returns. Nothing keeps the EntityManager open,…
Passwords are never stored in plaintext, and not with fast hashes (MD5, SHA-256) either, because GPU brute force is cheap. Spring Security uses a slow, salted hash, defaulting to BCrypt. That factory returns a DelegatingPasswordEncoder, which stores the hash with an algorithm id prefix: The…
As of Spring Security 6 (Spring Boot 3), WebSecurityConfigurerAdapter no longer exists. Instead of extending an adapter and overriding methods, you declare a SecurityFilterChain bean: Three migration points: - antMatchers / mvcMatchers become requestMatchers. - Lambda DSL replaces the .and() chaining style. - For different…
Because the entity returned by the repository is managed inside the persistence context, and Hibernate applies automatic dirty checking. Mechanism: when an entity is loaded, Hibernate keeps a snapshot of its property values. At flush time (before commit, or before a query that could be…
Both tell Hibernate to load an association in the same SQL statement, but they are declared at different levels. join fetch lives inside JPQL, tied to that one query: @EntityGraph is a declarative fetch plan attached to a method — including derived queries and methods…
Core requirement: an entity must equal itself across all states transient → managed → detached, and its hashCode must stay constant for the object's lifetime. Why the raw auto-increment ID fails: a freshly new-ed entity has a null id, producing one hashCode; after persist the…
The standard flow has four links, each with one job: 1. An authentication filter (e.g. UsernamePasswordAuthenticationFilter) extracts the credentials, wraps them in an unauthenticated UsernamePasswordAuthenticationToken, and hands it to the AuthenticationManager. 2. The AuthenticationManager (by default a ProviderManager) walks its AuthenticationProvider list to find one…
This is the lost update problem, solved with optimistic locking via @Version — a good fit because reads outnumber writes and users hold the data on a form for a long time (detached entity), so you cannot hold a database lock throughout. Mechanism: every UPDATE…
They differ in what triggers them, not in the resulting delete. - CascadeType.REMOVE: fires only when the parent is removed. Delete an Order and its OrderItems go with it. - orphanRemoval = true: fires when a child is detached from the parent, even though the…
The cause is filter ordering: a browser preflight OPTIONS carries no credentials (no cookie, no Authorization header). If the Spring Security filter chain runs before CORS handling, it sees an unauthenticated request and returns 401 immediately — the request never reaches the controller-level @CrossOrigin, so…
No. ResponseEntity is an HTTP concept (status code, headers, body) and belongs to the controller layer. A service should return business data (entities, DTOs) or throw business exceptions; the controller or a @RestControllerAdvice translates them into HTTP. Problems when a service returns ResponseEntity: - The…
PostgreSQL + MongoDB is the easy case: two different starters (spring-boot-starter-data-jpa and spring-boot-starter-data-mongodb) auto-configure independently, each reading its own properties. Two databases of the same kind (two Postgres) is the hard case: auto-configuration creates only one DataSource, so you declare beans for each yourself. Case…
You only add a starter + a JDBC driver and declare spring.datasource.; Spring Boot creates a DataSource with a connection pool (HikariCP by default), and with JPA it also creates the EntityManagerFactory, transaction manager and repositories. That is auto-configuration: Spring Boot sees which classes are…
Three main ways: put a stereotype annotation on your own class so component scanning finds it, write a @Bean method in a @Configuration class that creates the object yourself, or declare <bean in XML (the old way). All three produce a bean definition in the…
JPA/Hibernate is an ORM: you work with entities, it generates SQL, tracks changes and flushes to the DB itself. MyBatis is a SQL mapper: you write the SQL (XML or annotations), MyBatis only binds parameters and maps results to objects. The core difference: who controls…
At its core Spring is one big Factory (the IoC container) that creates and manages objects, plus Proxies that wrap behavior (transactions, caching, security) around your methods. Other patterns show up in individual modules. Pattern Where in Spring ------ Factory BeanFactory/ApplicationContext create beans; FactoryBean for…