20 questions · untimed

Java interview: Spring Boot round

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?

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?

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?

Question 4 · medium

@Service, @Repository and @Controller are all specialisations of @Component. What does @Repository add beyond being picked up by component scanning?

Question 5 · hard

A singleton ExportService needs a fresh CsvWriter 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?

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?

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?

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?

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?

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?

Question 11 · easy

This Spring Data JPA repository has no implementation class anywhere in the project:

public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByEmail(String email);
}

What happens when a service calls userRepository.findByEmail("a@b.in")?

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?

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?

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?

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?

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?

Question 17 · medium

InvoiceException extends Exception (a checked exception).

@Transactional
public void placeOrder(Order order) throws InvoiceException {
    orderRepository.save(order);
    invoiceClient.send(order); // throws InvoiceException
}

With default Spring settings, what happens to the saved order when send throws?

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?

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?

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?

Back to all rounds