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.mid
With default settings, what happens to the saved order when this method throws?
@Transactional public void place(Order order) throws IOException { orderRepository.save(order); throw new IOException("printer offline"); }- AThe transaction rolls back and the order is not saved
- BThe transaction commits, so the order is saved
- CSpring throws
UnexpectedRollbackExceptioninstead - DThe method runs without any transaction at all
Show answer
Answer: B (The transaction commits, so the order is saved)
By default
@Transactionalrolls back only onRuntimeExceptionandError. A checked exception likeIOExceptionlets the transaction commit, so the order is saved, and the exception still propagates to the caller. AddrollbackFor = Exception.classto roll back on checked exceptions too. - 2.hard
A controller calls
checkout(). How many physical transactions are used?@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) { /* ... */ } }- ATwo:
auditgets its own new transaction - BNone: self-invocation disables both annotations
- COne:
auditjoins the checkout transaction - DNone: startup fails with a proxy error
Show answer
Answer: C (One:
auditjoins the checkout transaction)The controller calls
checkoutthrough the proxy, so one transaction starts.auditis invoked onthis, bypassing the proxy, so itsREQUIRES_NEWis never applied and it simply runs inside the existing transaction. Movingauditto another bean, or using AspectJ mode, would give it its own transaction. - ATwo:
- 3.easy
Which annotation is not part of
@SpringBootApplication?- A
@ComponentScan - B
@SpringBootConfiguration - C
@EnableAutoConfiguration - D
@EnableWebMvc
Show answer
Answer: D (
@EnableWebMvc)@SpringBootApplicationcombines@SpringBootConfiguration,@EnableAutoConfigurationand@ComponentScan.@EnableWebMvcis 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. - A
- 4.easy
What does
GET /orders, with no query string, return?@GetMapping("/orders") public List<OrderDto> list(@RequestParam String status) { return orderService.findByStatus(status); }- A400 Bad Request: the parameter is required
- B200 OK, with
statusset tonull - C200 OK, with
statusset to an empty string - D500, from a
NullPointerExceptionin the service
Show answer
Answer: A (400 Bad Request: the parameter is required)
@RequestParamis required by default, so a missing parameter raisesMissingServletRequestParameterException, which Spring MVC turns into a 400. Userequired = false,Optional<String>or adefaultValueto make it optional. - 5.easy
You add Actuator to a Spring Boot 3 app and set no
management.*properties. Which endpoints are exposed over HTTP?- AAll endpoints except
shutdown - B
healthandinfo - COnly
health - D
health,infoandmetrics
Show answer
Answer: C (Only
health)By default only the
healthendpoint is exposed over HTTP. Every other endpoint,infoincluded, has to be opted into withmanagement.endpoints.web.exposure.include, which is a deliberate safeguard because endpoints likeenvandheapdumpare sensitive. - AAll endpoints except
- 6.mid
The packaged
application.ymlsetsserver.port: 8080, the environment hasSERVER_PORT=9090, and the app is started with--server.port=7070. Which port is used?- A8080
- B7070
- C9090
- 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.mid
Which JPA association is fetched eagerly by default?
- A
@ManyToOne - B
@OneToMany - C
@ManyToMany - D
@ElementCollection
Show answer
Answer: A (
@ManyToOne)In JPA,
@ManyToOneand@OneToOnedefault toFetchType.EAGER, while collection mappings (@OneToMany,@ManyToMany,@ElementCollection) default toLAZY. Many teams setfetch = FetchType.LAZYon to-one associations explicitly to avoid unwanted joins and extra queries. - A
- 8.mid
Which repository method makes Spring Data JPA run an additional count query?
- A
List<Order> findByStatus(Status s, Pageable p) - B
Slice<Order> findByStatus(Status s, Pageable p) - C
Stream<Order> findByStatus(Status s, Sort sort) - D
Page<Order> findByStatus(Status s, Pageable p)
Show answer
Answer: D (
Page<Order> findByStatus(Status s, Pageable p))A
Pageexposes the total number of elements and pages, so Spring Data issues an extra count query. ASliceonly fetches one additional row to know whether a next slice exists, and aListjust applies the limit and offset without metadata. - A
- 9.easy
A user's only granted authority is
ADMIN. Can they call a method annotated@PreAuthorize("hasRole('ADMIN')")?- AYes:
hasRolematches the authority name exactly as given - BYes, but only when
jsr250Enabledis set to true - CNo:
hasRolerequires@Securedto be enabled - DNo:
hasRolelooks for the authorityROLE_ADMIN
Show answer
Answer: D (No:
hasRolelooks for the authorityROLE_ADMIN)hasRole('ADMIN')adds the defaultROLE_prefix and checks for the authorityROLE_ADMIN, so a bareADMINauthority is denied with a 403. UsehasAuthority('ADMIN')to match the exact string, or grant the authority asROLE_ADMIN. - AYes:
- 10.mid
With the default key generator, which cache key is used for the call
find("42", true)?@Cacheable("users") public User find(String id, boolean includeDeleted) { /* ... */ }- AA
SimpleKeyholding both"42"andtrue - BThe string
"42", the first parameter only - CThe combined
hashCode()of both parameters - DThe method name followed by the first parameter
Show answer
Answer: A (A
SimpleKeyholding both"42"andtrue)SimpleKeyGeneratorusesSimpleKey.EMPTYfor no parameters, the parameter itself for exactly one, and aSimpleKeywrapping all parameters for several. It has not relied on hash codes alone since Spring 4.0, which avoids collisions. Sofind("42", false)is cached under a different key. - AA
- 11.hard
Does
orderServicereceive the sameAuditLoginstance that is registered as a bean?@Configuration(proxyBeanMethods = false) public class AppConfig { @Bean public AuditLog auditLog() { return new AuditLog(); } @Bean public OrderService orderService() { return new OrderService(auditLog()); } }- AYes: Spring intercepts
auditLog()and returns the bean - BNo:
auditLog()is a plain call that makes a new object - CYes: every
@Beanmethod result is cached as a singleton - 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 = falsethe configuration class is not CGLIB-proxied, soauditLog()is an ordinary Java call andOrderServicegets a second, unmanagedAuditLog. With the defaultproxyBeanMethods = truethe call would be intercepted and return the singleton. DeclaringAuditLogas a method parameter works in both modes. - AYes: Spring intercepts
- 12.mid
OrderControllertakes anOrderService(a@Service) in its constructor, and the test declares no mock for it. What happens?@WebMvcTest(OrderController.class) class OrderControllerTest { @Autowired MockMvc mvc; @Test void lists() throws Exception { mvc.perform(get("/api/orders")).andExpect(status().isOk()); } }- AIt passes: the real
OrderServiceis loaded too - BIt passes: Spring injects
nullfor the service - CThe context fails to load: no
OrderServicebean - DIt fails with a 404: no controller gets registered
Show answer
Answer: C (The context fails to load: no
OrderServicebean)@WebMvcTestonly loads web-layer components such as controllers,@ControllerAdvice, filters and converters; regular@Servicebeans are not scanned. The controller cannot be created without anOrderService, so the application context fails to load. Declaring@MockitoBean OrderService orderServicefixes it. - AIt passes: the real
- 13.easy
By default, what happens to data saved inside a
@DataJpaTesttest method?- AIt is committed and visible to later tests
- BIt is rolled back at the end of each test
- CIt is kept until the whole test class ends
- DIt is committed only if the test method passes
Show answer
Answer: B (It is rolled back at the end of each test)
@DataJpaTesttests 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 configuredDataSource, unless you use@AutoConfigureTestDatabase(replace = Replace.NONE). - 14.mid
Two services inject each other through
@Autowiredfields. What happens in a Spring Boot 3 app with default settings?- AStartup fails: circular references are prohibited
- BSpring resolves it with early bean references
- CThe app starts, but one of the fields stays
null - 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=truerestores the old behavior, but breaking the cycle is the real fix. - 15.hard
inventoryis another bean whosereserve()method is@Transactionalwith default settings, and it throwsIllegalStateException. What happens whenplace()returns?@Transactional public void place(Order order) { orderRepository.save(order); try { inventory.reserve(order); } catch (IllegalStateException e) { log.warn("Reservation failed, continuing"); } }- AThe order commits, since the exception was caught
- BOnly the reservation rolls back; the order still commits
- CThe commit fails with
UnexpectedRollbackException - DSpring retries
reserve()in a new transaction
Show answer
Answer: C (The commit fails with
UnexpectedRollbackException)Both methods share one physical transaction because of
REQUIREDpropagation. When the exception leavesreserve()through its proxy, Spring marks the shared transaction rollback-only; catching it inplace()doesn't undo that. At commit Spring rolls back instead and throwsUnexpectedRollbackException. If partial success is intended, run the inner call withREQUIRES_NEW. - 16.easy
How often does this method run?
@Scheduled(cron = "0 */5 * * * *") public void refreshRates() { /* ... */ }- AEvery 5 seconds
- BEvery 5 hours, at minute 0
- CNever: Spring cron needs five fields
- 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.mid
An app has both
spring-boot-starter-webandspring-boot-starter-webfluxon the classpath and no extra settings. What does Boot configure?- ASpring WebFlux on Reactor Netty
- BSpring MVC on embedded Tomcat
- CBoth stacks, on two separate ports
- 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 withspring.main.web-application-type=reactive. - 18.easy
Which annotation replaces Spring Boot's deprecated
@MockBeanfor putting a Mockito mock into the test's application context?- A
@Mock - B
@InjectMocks - C
@MockitoBean - D
@TestBean
Show answer
Answer: C (
@MockitoBean)@MockitoBean, added in Spring Framework 6.2, replaces or adds a bean in theApplicationContextwith a Mockito mock. Boot's@MockBeanwas deprecated in 3.4 and removed in 4.0. Plain Mockito@Mockand@InjectMockswork outside the Spring context, and@TestBeanoverrides a bean with an instance from a factory method. - A
- 19.easy
In a class annotated
@Controller(not@RestController), what does returning"orders"from a@GetMappingmethod do by default?- AWrites the text
ordersto the response body - BReturns the JSON string
"orders", in quotes - CRedirects the browser to the
/orderspath - DResolves a view named
ordersand renders it
Show answer
Answer: D (Resolves a view named
ordersand renders it)Without
@ResponseBody, aStringreturned from a@Controllermethod is a logical view name, which aViewResolvermaps to a template such asorders.html.@RestControlleror@ResponseBodywould write it to the body instead, and a redirect needs theredirect:prefix. - AWrites the text
- 20.mid
In Spring Boot 3.4 and later, with default settings, what happens to in-flight HTTP requests when the app receives
SIGTERM?- AThey get a grace period to finish
- BThe server stops at once and drops them
- CThey are handed off to another instance
- 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 setserver.shutdown=graceful. - 21.mid
A bean uses
@PostConstruct, implementsInitializingBean, and also declares a custom init method. In what order are they called?- A
afterPropertiesSet(),@PostConstruct, then the init method - BThe init method,
@PostConstruct, thenafterPropertiesSet() - C
@PostConstruct,afterPropertiesSet(), then the init method - D
@PostConstruct, the init method, thenafterPropertiesSet()
Show answer
Answer: C (
@PostConstruct,afterPropertiesSet(), then the init method)Spring calls
@PostConstructmethods first, thenInitializingBean.afterPropertiesSet(), then the custom init method. Destruction follows the same pattern:@PreDestroy,DisposableBean.destroy(), then the custom destroy method. - A