Pick an option and check it. The explanation shows after each answer. Take as long as you like; nothing is timed and nothing is sent.
20 questions
Question 1 · easy
An interviewer asks why most Spring Boot 3 teams prefer constructor injection over @Autowired on fields. Which answer is the strongest?
With constructor injection every required dependency is a constructor argument, so the fields can be final and the object is never created without them. Tests need no Spring context or reflection: new OrderService(fakeRepo) is enough. Field injection still works in Spring Boot 3, but it hides dependencies and leaves them null outside the container; constructor injection actually makes circular dependencies fail fast instead of allowing them.
Question 2 · easy
In Spring Boot 3, a @Service class keeps a counter in an instance field:
@Service
public class VisitService {
private int visits;
public int recordVisit() {
return ++visits;
}
}
Two controllers inject VisitService and many users call it at the same time. What is true?
The default bean scope is singleton: the container creates one instance and injects that same object everywhere. Every request thread therefore shares the visits field, and ++visits is a read-modify-write that can lose updates under concurrency. Keep singleton beans stateless, or use something like AtomicInteger or a database when shared state is really needed.
Question 3 · medium
Spring Boot 3 fails at startup with NoUniqueBeanDefinitionException: expected single matching bean but found 2: cardGateway,upiGateway.
public interface PaymentGateway { void charge(long paise); }
@Component
public class UpiGateway implements PaymentGateway { /* ... */ }
@Component
public class CardGateway implements PaymentGateway { /* ... */ }
@Service
public class CheckoutService {
private final PaymentGateway gateway;
public CheckoutService(PaymentGateway gateway) { this.gateway = gateway; }
}
Checkout should use UPI. Which change fixes it?
Injection is by type, and two beans implement PaymentGateway, so Spring cannot pick one. @Qualifier("upiGateway") names the bean to inject (the default bean name is the class name with a lower-case first letter). Marking UpiGateway with @Primary would also work when it should be the default everywhere; @Autowired or @Lazy do not remove the ambiguity.
Question 4 · medium
@Service, @Repository and @Controller are all specialisations of @Component. What does @Repository add beyond being picked up by component scanning?
All stereotype annotations register the class as a bean, and they also document the layer the class belongs to. @Repository additionally marks the class for persistence exception translation, so a caller sees a consistent DataAccessException (for example DataIntegrityViolationException) instead of a vendor- or JPA-specific exception. It does not start transactions or change the scope; beans stay singletons unless told otherwise.
Question 5 · hard
A singleton ExportService needs a freshCsvWriter for every export, because CsvWriter keeps per-export state. CsvWriter is a @Component with @Scope("prototype") and has its own injected dependencies. How should ExportService get a new instance on each call?
A prototype bean injected into a singleton is created once, when the singleton is built, and then reused for the singleton's whole life. Asking the container each time, by calling getObject() on an injected ObjectProvider of CsvWriter (or through a @Lookup method), returns a new, fully injected instance per call. Making ExportService prototype only moves the problem to whoever injects it, and new bypasses the container, so CsvWriter's own dependencies would be null.
Question 6 · easy
In Spring Boot 3, a handler method returns the string "hello". In a @Controller class the request fails while looking for a view or template named hello; in a @RestController class the client receives hello as the response body. Why the difference?
@RestController is a composed annotation: @Controller with @ResponseBody applied to every handler method. With @ResponseBody, the return value is converted by an HTTP message converter (plain text for a String, JSON for objects via Jackson). In a plain @Controller, a returned String is treated as a logical view name for a template engine.
Question 7 · easy
A client calls GET /users/42/orders?status=PAID, handled by a method mapped with @GetMapping("/users/{id}/orders"). Which parameter list binds 42 and PAID correctly?
@PathVariable binds a {placeholder} segment of the URL path, which identifies the resource, here user 42. @RequestParam binds a query-string parameter after ?, typically a filter, sort or page option. @RequestBody reads the HTTP request body, which a GET request like this does not have. Note that @RequestParam is required by default, so omitting status would give 400 unless you set required = false or a defaultValue.
Question 8 · medium
spring-boot-starter-validation is on the classpath of this Spring Boot 3 app.
public record SignupRequest(@NotBlank String name, @Email String email) {}
@PostMapping("/signup")
public ResponseEntity<Void> signup(@RequestBody SignupRequest req) {
userService.register(req);
return ResponseEntity.ok().build();
}
A request with "name": "" and "email": "abc" is accepted and saved. Which change makes Spring reject it with 400 Bad Request?
Constraint annotations on a class only describe the rules; Spring MVC runs Bean Validation on a @RequestBody argument only when the parameter is marked @Valid (or @Validated). With it, a violation throws MethodArgumentNotValidException, which Spring turns into a 400 response by default and which a @RestControllerAdvice can map to a clearer error body. @NotNull would still accept an empty string, and a request DTO is not a bean.
Question 9 · medium
POST /api/books creates a book and the new book gets id 17. Following REST conventions, what should the Spring Boot 3 controller return?
201 Created is the status for a request that created a new resource, and the Location header tells the client the URL of that resource; returning the created representation in the body saves a follow-up GET. 200 works but hides the fact that something was created, and 204 sends nothing back, not even the new id. 202 Accepted means the work was queued and has not finished yet, which is not the case here.
Question 10 · medium
Several controllers repeat the same try/catch that turns BookNotFoundException into a 404 response. What is the recommended Spring Boot 3 way to handle this?
@RestControllerAdvice (@ControllerAdvice plus @ResponseBody) holds exception handlers that apply to all controllers, so the mapping from an exception to an HTTP status and error body lives in one place. Controllers then just throw, and stay focused on the happy path. Without a handler, an unhandled exception becomes a 500, and returning null from a @RestController gives 200 with an empty body, not 404.
Question 11 · easy
This Spring Data JPA repository has no implementation class anywhere in the project:
What happens when a service calls userRepository.findByEmail("a@b.in")?
Spring Data parses derived query method names: findBy followed by property names and keywords such as And, OrderBy or Containing. At startup it builds the JPQL (where u.email = ?1) and generates a proxy implementation of the interface. If the property does not exist on the entity, the application fails at startup, which catches typos early; @Query is only needed when the name would get too long or the query is not expressible this way.
Question 12 · medium
The app sets spring.jpa.open-in-view=false.
@Entity
public class Author {
@Id @GeneratedValue private Long id;
@OneToMany(mappedBy = "author")
private List<Book> books;
// getters
}
@GetMapping("/authors/{id}/book-count")
public int bookCount(@PathVariable Long id) {
Author a = authorRepository.findById(id).orElseThrow();
return a.getBooks().size(); // LazyInitializationException
}
Which change fixes the exception properly?
@OneToMany is lazy by default, so findById returns an author whose books is an uninitialised proxy collection. findById ran in its own short transaction; once it ended the entity was detached, and touching the collection later has no session to load from. Reading it inside a transactional service method, or fetching it up front with join fetch or an @EntityGraph, fixes it; for a count, a countByAuthorId query is even cheaper. Entities are not Spring beans, so @Transactional on one does nothing.
Question 13 · hard
With SQL logging on, this Spring Boot 3 method runs 101 queries for 100 departments.
@Entity
public class Department {
@Id private Long id;
@OneToMany(mappedBy = "department")
private List<Employee> employees;
}
@Transactional(readOnly = true)
public int headcount() {
int total = 0;
for (Department d : departmentRepository.findAll()) {
total += d.getEmployees().size();
}
return total;
}
Which change loads the departments with their employees in a single query?
This is the N+1 problem: one query loads the departments, then each lazy getEmployees() fires one more query per department. A join fetch (or @EntityGraph(attributePaths = "employees")) tells JPA to load the collection in the same SQL join. Switching to EAGER does not help here: findAll() runs a JPQL query that does not join the collection, so Hibernate still loads each eager collection with its own select, and now does so on every load of a Department too.
Question 14 · easy
A candidate is asked what a class needs at minimum to be a valid JPA @Entity in a Spring Boot 3 project (Hibernate 6, jakarta.persistence). Which answer is correct?
An entity needs @Entity, a primary key marked with @Id, and a no-arg constructor that is public or protected, because the JPA provider instantiates it by reflection before filling the fields. @Table and @Column are optional and only override the default table and column names. Serializable is not required, and JpaRepository is the interface for the repository, not something an entity extends.
Question 15 · medium
A User entity has a passwordHash field, a lazy @OneToMany list of orders, and each Order has a @ManyToOne back to its User. A junior returns User entities straight from a @RestController. What design should the team adopt?
Exposing entities couples the API to the database schema and leaks fields such as passwordHash. It also makes Jackson walk lazy associations, which causes extra queries or LazyInitializationException, and a bidirectional User/Order pair can recurse endlessly. A DTO decides exactly what the API returns, can change independently of the table, and is filled while the transaction is still open.
Question 16 · medium
A controller calls importAll(rows). When saving an address throws a RuntimeException, that row's customer stays saved in the database. Repositories are injected (omitted).
@Service
public class ImportService {
public void importAll(List<Row> rows) {
for (Row r : rows) {
importOne(r);
}
}
@Transactional
public void importOne(Row r) {
customerRepo.save(r.customer());
addressRepo.save(r.address()); // throws for a bad row
}
}
Why is the customer not rolled back?
@Transactional works through a proxy around the bean: only calls that come in through the proxy are wrapped in a transaction. A call from one method to another on the same object uses this, so the annotation on importOne is ignored, and each repository save runs in its own transaction and commits. Move importOne to a separate bean (or make the outer method transactional) so the call goes through a proxy.
Question 17 · medium
InvoiceException extends Exception (a checked exception).
With default Spring settings, what happens to the saved order when send throws?
Spring's default rollback rule follows EJB: a RuntimeException or Error rolls the transaction back, while a checked exception is treated as a business outcome and the transaction commits. To roll back here, declare @Transactional(rollbackFor = InvoiceException.class), or make the exception unchecked. This default surprises many candidates, which is why interviewers ask it.
Question 18 · easy
application.properties contains server.port=9090 and app.sms.enabled=false. application-prod.properties contains only app.sms.enabled=true. The app starts with spring.profiles.active=prod. What are the effective values?
Spring Boot always loads application.properties, then adds application-{profile}.properties (here application-prod.properties) for each active profile, with the profile-specific values taking precedence. Keys missing from the profile file keep their base values, so the base file holds shared defaults and each profile overrides only what differs. The same spring.profiles.active switch also turns on beans annotated @Profile("prod").
Question 19 · easy
A payment client needs five related settings: base URL, connect timeout, read timeout, retry count and API key. What is the recommended way to bring them into Spring Boot 3 code?
@ConfigurationProperties binds a whole group of keys to one typed object: durations, numbers and nested values are converted for you, relaxed binding accepts payment.base-url or PAYMENT_BASEURL, and the class can be validated with @Validated. @Value is fine for a single value, but scattered across classes it duplicates key names and has no single place to see or check the configuration. Environment variables still work, because Spring maps them onto the same properties.
Question 20 · hard
placeOrder is @Transactional. When payment fails it throws a PaymentFailedException (unchecked) and the order is correctly rolled back. A new rule says every payment attempt, including failed ones, must leave a row in payment_attempt. How should this be designed?
REQUIRES_NEW suspends the caller's transaction and runs the method in its own transaction, which commits when that method returns, so the audit row survives when placeOrder later rolls back. It must be called through another bean's proxy: a call to a method on this (and Spring does not proxy private methods) ignores the annotation. Saving inside placeOrder is rolled back with the order, and noRollbackFor would commit the half-placed order too.
Your answers stay in this browser tab. Nothing is sent or saved.