pencils ready ✎

Spring Boot MCQs multiple-choice questions with answers & explanations

All 21 Spring Boot quiz questions on one page. Pick an answer in your head, then open Show answer to check it and read why. Want a score and a timer? Take them as a quiz instead.

  1. 1.

    With default settings, what happens to the saved order when this method throws?

    mid
    @Transactional
    public void place(Order order) throws IOException {
        orderRepository.save(order);
        throw new IOException("printer offline");
    }
    1. AThe transaction rolls back and the order is not saved
    2. BThe transaction commits, so the order is saved
    3. CSpring throws UnexpectedRollbackException instead
    4. DThe method runs without any transaction at all
    Show answer

    Answer: B (The transaction commits, so the order is saved)

    By default @Transactional rolls back only on RuntimeException and Error. A checked exception like IOException lets the transaction commit, so the order is saved, and the exception still propagates to the caller. Add rollbackFor = Exception.class to roll back on checked exceptions too.

  2. 2.

    A controller calls checkout(). How many physical transactions are used?

    hard
    @Service
    public class CheckoutService {
        @Transactional
        public void checkout(Cart cart) {
            audit(cart); // plain call on "this"
        }
    
        @Transactional(propagation = Propagation.REQUIRES_NEW)
        public void audit(Cart cart) { /* ... */ }
    }
    1. ATwo: audit gets its own new transaction
    2. BNone: self-invocation disables both annotations
    3. COne: audit joins the checkout transaction
    4. DNone: startup fails with a proxy error
    Show answer

    Answer: C (One: audit joins the checkout transaction)

    The controller calls checkout through the proxy, so one transaction starts. audit is invoked on this, bypassing the proxy, so its REQUIRES_NEW is never applied and it simply runs inside the existing transaction. Moving audit to another bean, or using AspectJ mode, would give it its own transaction.

  3. 3.

    Which annotation is not part of @SpringBootApplication?

    easy
    1. A@ComponentScan
    2. B@SpringBootConfiguration
    3. C@EnableAutoConfiguration
    4. D@EnableWebMvc
    Show answer

    Answer: D (@EnableWebMvc)

    @SpringBootApplication combines @SpringBootConfiguration, @EnableAutoConfiguration and @ComponentScan. @EnableWebMvc is not part of it; adding it to a Boot app actually switches off Boot's Spring MVC auto-configuration, because it signals that you want full manual control.

  4. 4.

    What does GET /orders, with no query string, return?

    easy
    @GetMapping("/orders")
    public List<OrderDto> list(@RequestParam String status) {
        return orderService.findByStatus(status);
    }
    1. A400 Bad Request: the parameter is required
    2. B200 OK, with status set to null
    3. C200 OK, with status set to an empty string
    4. D500, from a NullPointerException in the service
    Show answer

    Answer: A (400 Bad Request: the parameter is required)

    @RequestParam is required by default, so a missing parameter raises MissingServletRequestParameterException, which Spring MVC turns into a 400. Use required = false, Optional<String> or a defaultValue to make it optional.

  5. 5.

    You add Actuator to a Spring Boot 3 app and set no management.* properties. Which endpoints are exposed over HTTP?

    easy
    1. AAll endpoints except shutdown
    2. Bhealth and info
    3. COnly health
    4. Dhealth, info and metrics
    Show answer

    Answer: C (Only health)

    By default only the health endpoint is exposed over HTTP. Every other endpoint, info included, has to be opted into with management.endpoints.web.exposure.include, which is a deliberate safeguard because endpoints like env and heapdump are sensitive.

  6. 6.

    The packaged application.yml sets server.port: 8080, the environment has SERVER_PORT=9090, and the app is started with --server.port=7070. Which port is used?

    mid
    1. A8080
    2. B7070
    3. C9090
    4. DStartup fails
    Show answer

    Answer: B (7070)

    Command-line arguments take precedence over OS environment variables, which in turn override config files such as application.yml. So 7070 wins. Conflicting sources never fail startup; the highest-precedence source simply wins.

  7. 7.

    Which JPA association is fetched eagerly by default?

    mid
    1. A@ManyToOne
    2. B@OneToMany
    3. C@ManyToMany
    4. D@ElementCollection
    Show answer

    Answer: A (@ManyToOne)

    In JPA, @ManyToOne and @OneToOne default to FetchType.EAGER, while collection mappings (@OneToMany, @ManyToMany, @ElementCollection) default to LAZY. Many teams set fetch = FetchType.LAZY on to-one associations explicitly to avoid unwanted joins and extra queries.

  8. 8.

    Which repository method makes Spring Data JPA run an additional count query?

    mid
    1. AList<Order> findByStatus(Status s, Pageable p)
    2. BSlice<Order> findByStatus(Status s, Pageable p)
    3. CStream<Order> findByStatus(Status s, Sort sort)
    4. DPage<Order> findByStatus(Status s, Pageable p)
    Show answer

    Answer: D (Page<Order> findByStatus(Status s, Pageable p))

    A Page exposes the total number of elements and pages, so Spring Data issues an extra count query. A Slice only fetches one additional row to know whether a next slice exists, and a List just applies the limit and offset without metadata.

  9. 9.

    A user's only granted authority is ADMIN. Can they call a method annotated @PreAuthorize("hasRole('ADMIN')")?

    easy
    1. AYes: hasRole matches the authority name exactly as given
    2. BYes, but only when jsr250Enabled is set to true
    3. CNo: hasRole requires @Secured to be enabled
    4. DNo: hasRole looks for the authority ROLE_ADMIN
    Show answer

    Answer: D (No: hasRole looks for the authority ROLE_ADMIN)

    hasRole('ADMIN') adds the default ROLE_ prefix and checks for the authority ROLE_ADMIN, so a bare ADMIN authority is denied with a 403. Use hasAuthority('ADMIN') to match the exact string, or grant the authority as ROLE_ADMIN.

  10. 10.

    With the default key generator, which cache key is used for the call find("42", true)?

    mid
    @Cacheable("users")
    public User find(String id, boolean includeDeleted) { /* ... */ }
    1. AA SimpleKey holding both "42" and true
    2. BThe string "42", the first parameter only
    3. CThe combined hashCode() of both parameters
    4. DThe method name followed by the first parameter
    Show answer

    Answer: A (A SimpleKey holding both "42" and true)

    SimpleKeyGenerator uses SimpleKey.EMPTY for no parameters, the parameter itself for exactly one, and a SimpleKey wrapping all parameters for several. It has not relied on hash codes alone since Spring 4.0, which avoids collisions. So find("42", false) is cached under a different key.

  11. 11.

    Does orderService receive the same AuditLog instance that is registered as a bean?

    hard
    @Configuration(proxyBeanMethods = false)
    public class AppConfig {
        @Bean
        public AuditLog auditLog() { return new AuditLog(); }
    
        @Bean
        public OrderService orderService() { return new OrderService(auditLog()); }
    }
    1. AYes: Spring intercepts auditLog() and returns the bean
    2. BNo: auditLog() is a plain call that makes a new object
    3. CYes: every @Bean method result is cached as a singleton
    4. DNo: startup fails with a duplicate bean definition
    Show answer

    Answer: B (No: auditLog() is a plain call that makes a new object)

    With proxyBeanMethods = false the configuration class is not CGLIB-proxied, so auditLog() is an ordinary Java call and OrderService gets a second, unmanaged AuditLog. With the default proxyBeanMethods = true the call would be intercepted and return the singleton. Declaring AuditLog as a method parameter works in both modes.

  12. 12.

    OrderController takes an OrderService (a @Service) in its constructor, and the test declares no mock for it. What happens?

    mid
    @WebMvcTest(OrderController.class)
    class OrderControllerTest {
        @Autowired MockMvc mvc;
    
        @Test
        void lists() throws Exception {
            mvc.perform(get("/api/orders")).andExpect(status().isOk());
        }
    }
    1. AIt passes: the real OrderService is loaded too
    2. BIt passes: Spring injects null for the service
    3. CThe context fails to load: no OrderService bean
    4. DIt fails with a 404: no controller gets registered
    Show answer

    Answer: C (The context fails to load: no OrderService bean)

    @WebMvcTest only loads web-layer components such as controllers, @ControllerAdvice, filters and converters; regular @Service beans are not scanned. The controller cannot be created without an OrderService, so the application context fails to load. Declaring @MockitoBean OrderService orderService fixes it.

  13. 13.

    By default, what happens to data saved inside a @DataJpaTest test method?

    easy
    1. AIt is committed and visible to later tests
    2. BIt is rolled back at the end of each test
    3. CIt is kept until the whole test class ends
    4. DIt is committed only if the test method passes
    Show answer

    Answer: B (It is rolled back at the end of each test)

    @DataJpaTest tests are transactional and roll back at the end of each test, which keeps tests isolated. By default they also run against an embedded in-memory database that replaces any configured DataSource, unless you use @AutoConfigureTestDatabase(replace = Replace.NONE).

  14. 14.

    Two services inject each other through @Autowired fields. What happens in a Spring Boot 3 app with default settings?

    mid
    1. AStartup fails: circular references are prohibited
    2. BSpring resolves it with early bean references
    3. CThe app starts, but one of the fields stays null
    4. DIt starts, then overflows the stack on first call
    Show answer

    Answer: A (Startup fails: circular references are prohibited)

    Spring can technically break a field or setter injection cycle with early references, but since Spring Boot 2.6 circular references are prohibited by default, so startup fails and the cycle is reported. spring.main.allow-circular-references=true restores the old behavior, but breaking the cycle is the real fix.

  15. 15.

    inventory is another bean whose reserve() method is @Transactional with default settings, and it throws IllegalStateException. What happens when place() returns?

    hard
    @Transactional
    public void place(Order order) {
        orderRepository.save(order);
        try {
            inventory.reserve(order);
        } catch (IllegalStateException e) {
            log.warn("Reservation failed, continuing");
        }
    }
    1. AThe order commits, since the exception was caught
    2. BOnly the reservation rolls back; the order still commits
    3. CThe commit fails with UnexpectedRollbackException
    4. DSpring retries reserve() in a new transaction
    Show answer

    Answer: C (The commit fails with UnexpectedRollbackException)

    Both methods share one physical transaction because of REQUIRED propagation. When the exception leaves reserve() through its proxy, Spring marks the shared transaction rollback-only; catching it in place() doesn't undo that. At commit Spring rolls back instead and throws UnexpectedRollbackException. If partial success is intended, run the inner call with REQUIRES_NEW.

  16. 16.

    How often does this method run?

    easy
    @Scheduled(cron = "0 */5 * * * *")
    public void refreshRates() { /* ... */ }
    1. AEvery 5 seconds
    2. BEvery 5 hours, at minute 0
    3. CNever: Spring cron needs five fields
    4. DEvery 5 minutes, at second 0
    Show answer

    Answer: D (Every 5 minutes, at second 0)

    Spring cron expressions have six fields: second, minute, hour, day of month, month and day of week. 0 */5 * * * * means second 0 of every fifth minute. Classic Unix cron has five fields; Spring adds seconds at the front.

  17. 17.

    An app has both spring-boot-starter-web and spring-boot-starter-webflux on the classpath and no extra settings. What does Boot configure?

    mid
    1. ASpring WebFlux on Reactor Netty
    2. BSpring MVC on embedded Tomcat
    3. CBoth stacks, on two separate ports
    4. DNothing: startup fails as ambiguous
    Show answer

    Answer: B (Spring MVC on embedded Tomcat)

    With both starters present, Boot auto-configures Spring MVC, because many MVC applications add WebFlux just to use the reactive WebClient. You can force the reactive stack with spring.main.web-application-type=reactive.

  18. 18.

    Which annotation replaces Spring Boot's deprecated @MockBean for putting a Mockito mock into the test's application context?

    easy
    1. A@Mock
    2. B@InjectMocks
    3. C@MockitoBean
    4. D@TestBean
    Show answer

    Answer: C (@MockitoBean)

    @MockitoBean, added in Spring Framework 6.2, replaces or adds a bean in the ApplicationContext with a Mockito mock. Boot's @MockBean was deprecated in 3.4 and removed in 4.0. Plain Mockito @Mock and @InjectMocks work outside the Spring context, and @TestBean overrides a bean with an instance from a factory method.

  19. 19.

    In a class annotated @Controller (not @RestController), what does returning "orders" from a @GetMapping method do by default?

    easy
    1. AWrites the text orders to the response body
    2. BReturns the JSON string "orders", in quotes
    3. CRedirects the browser to the /orders path
    4. DResolves a view named orders and renders it
    Show answer

    Answer: D (Resolves a view named orders and renders it)

    Without @ResponseBody, a String returned from a @Controller method is a logical view name, which a ViewResolver maps to a template such as orders.html. @RestController or @ResponseBody would write it to the body instead, and a redirect needs the redirect: prefix.

  20. 20.

    In Spring Boot 3.4 and later, with default settings, what happens to in-flight HTTP requests when the app receives SIGTERM?

    mid
    1. AThey get a grace period to finish
    2. BThe server stops at once and drops them
    3. CThey are handed off to another instance
    4. DThey are paused and replayed on restart
    Show answer

    Answer: A (They get a grace period to finish)

    Since Boot 3.4, graceful shutdown is the default for the embedded servers: new requests are refused while active ones get up to spring.lifecycle.timeout-per-shutdown-phase (30 seconds by default) to complete. Earlier versions shut down immediately unless you set server.shutdown=graceful.

  21. 21.

    A bean uses @PostConstruct, implements InitializingBean, and also declares a custom init method. In what order are they called?

    mid
    1. AafterPropertiesSet(), @PostConstruct, then the init method
    2. BThe init method, @PostConstruct, then afterPropertiesSet()
    3. C@PostConstruct, afterPropertiesSet(), then the init method
    4. D@PostConstruct, the init method, then afterPropertiesSet()
    Show answer

    Answer: C (@PostConstruct, afterPropertiesSet(), then the init method)

    Spring calls @PostConstruct methods first, then InitializingBean.afterPropertiesSet(), then the custom init method. Destruction follows the same pattern: @PreDestroy, DisposableBean.destroy(), then the custom destroy method.

esc