🌱 Spring Boot MCQ Questions – Page 17
Questions 321–340 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsWhat is the output of this Spring Boot application?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(MyApp.class, args);
ServiceB serviceB = context.getBean(ServiceB.class);
System.out.println(serviceB.getDependencyInfo());
}
}
class ServiceA {
private static int instanceCount = 0;
public ServiceA() { instanceCount++; }
public String getInfo() { return "ServiceA instance count: " + instanceCount; }
}
class ServiceB {
private ServiceA serviceA;
public ServiceB(ServiceA serviceA) { this.serviceA = serviceA; }
public String getDependencyInfo() { return "ServiceB uses " + serviceA.getInfo(); }
}
@Configuration
class AppConfig {
@Bean
public ServiceA serviceA() { return new ServiceA(); }
@Bean
public ServiceB serviceB() { return new ServiceB(serviceA()); } // Calling serviceA() method
}
What will be the outcome of attempting to run this application?
java
package com.example.app;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;
@SpringBootApplication
public class ManualApp {
// No main method explicitly running this class as the primary source
}
class Runner {
public static void main(String[] args) {
SpringApplication app = new SpringApplication();
// app.setSources(ManualApp.class); is missing
app.run(args);
}
}
Given the Spring Boot code below, what will be the HTTP status code and response body when a POST request is made to `/users` with an empty JSON body `{}`?
java
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
class UserDto {
@NotBlank(message = "Name is required")
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
@RestController
class UserController {
@PostMapping("/users")
public String createUser(@Valid @RequestBody UserDto userDto) {
return "User created: " + userDto.getName();
}
}
@RestControllerAdvice
class GlobalValidationHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleValidationExceptions(MethodArgumentNotValidException ex) {
return ex.getBindingResult().getFieldError().getDefaultMessage();
}
}
What is the output of this code when accessing the '/calculate' endpoint?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
class CustomNotFoundException extends RuntimeException {
public CustomNotFoundException(String message) { super(message); }
}
@RestController
public class DataController {
@GetMapping("/calculate")
public String fetchData() {
throw new CustomNotFoundException("Data not found for calculation.");
}
@ExceptionHandler(CustomNotFoundException.class)
public ResponseEntity<String> handleCustomNotFound(CustomNotFoundException ex) {
return new ResponseEntity<>("Custom Error: " + ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
What HTTP status code is expected if the `TestService.update` method throws an `IllegalArgumentException`?
java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.mockito.Mockito.when;
import org.springframework.http.MediaType;
@WebMvcTest(controllers = TestController.class)
class TestControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private TestService testService;
@Test
void testUpdateInvalid() throws Exception {
when(testService.update(1L, "invalid")).thenThrow(new IllegalArgumentException("Invalid data"));
mockMvc.perform(put("/api/items/1")
.contentType(MediaType.TEXT_PLAIN)
.content("invalid"))
.andExpect(status().isBadRequest());
}
}
// Assuming TestController has:
// @RestController
// class TestController {
// @Autowired TestService service;
// @PutMapping("/api/items/{id}")
// public String updateItem(@PathVariable Long id, @RequestBody String data) { return service.update(id, data); }
// }
// @Service class TestService { public String update(Long id, String data) { return ""; } }
What is the output of this code?
java
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Collections;
public class SecureService {
@PreAuthorize("hasRole('USER')")
public String getUserFeature() { return "User Feature"; }
}
public class TestRunner {
public static void main(String[] args) {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("testUser", "pass", Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")))
);
SecureService service = new SecureService();
try { System.out.println(service.getUserFeature()); }
catch (Exception e) { System.out.println(e.getClass().getSimpleName()); }
}
}
Which of the following annotations marks a method to be executed immediately after a bean's properties have been set and initialization has completed, but before it is put into service?
What is the output of this Spring Boot application?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(MyApp.class, args);
String defaultMessage = context.getBean(String.class);
System.out.println(defaultMessage);
}
}
@Configuration
class AppConfig {
@Bean
public String firstString() { return "This is the first string."; }
@Bean
@Primary
public String secondString() { return "This is the primary string."; }
}
If a Spring application context has two beans of the same type, `myDefaultService` and `mySpecialService`, and `myDefaultService` is marked with `@Primary`, but a dependency is autowired with `@Autowired @Qualifier("mySpecialService")`, which bean will be injected?
What error will this Java code snippet, intended for a Spring Boot application, produce upon compilation?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/missing-import")
public ResponseEntity<String> getData() {
return ResponseEntity.status(NOT_FOUND).body("Data not found").build();
}
}
If multiple `@Bean` methods produce beans of the same type, and you want to designate one as the preferred candidate for auto-wiring when no specific bean name is provided, which annotation would you use on the preferred `@Bean` method?
To enable automatic JSR-303/380 bean validation for a `@RequestBody` object in a Spring Boot POST endpoint, which annotation should be placed before the `@RequestBody` parameter?
A client sends a POST request to `/api/items` with query parameters `name=Laptop&price=1200`. What error will occur when this controller method tries to process the request?
java
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class ItemCreationController {
@PostMapping("/items")
public String createItem(@RequestParam Item item) {
return "Item created: " + item.getName();
}
}
class Item {
private String name;
private double price;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
public Item() {}
}
What will be the output or error when running the main method of this Spring Boot application?
java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
@Configuration
@Component
class MyBean {
@Value("${my.missing.property}")
private String value;
}
public class PropertyApp {
public static void main(String[] args) {
new AnnotationConfigApplicationContext(PropertyApp.class.getPackage().getName());
}
}
A client sends a PUT request to `/api/products/1` with a JSON body `{"name": "New Product Name"}`. What kind of error will occur at runtime?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/products")
public class ProductController {
@PutMapping("/{id}")
public ResponseEntity<Product> updateProduct(@PathVariable Long id, Product productDetails) {
// Assume productRepository.findById(id) and save methods exist
// This line would typically involve fetching and updating
return ResponseEntity.ok(productDetails);
}
}
// Assume Product class exists
To extract a value from the URI path, such as `id` from `/api/products/{id}`, which Spring annotation should be used on a method parameter?
What is the expected value of the `id` path variable when performing this MockMvc request?
java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
@WebMvcTest(controllers = TestController.class)
class TestControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testGetWithPathVariable() throws Exception {
mockMvc.perform(get("/api/items/{id}", 123))
.andExpect(jsonPath("$.itemId").value(123));
}
}
// Assuming TestController has:
// @RestController
// class TestController {
// @GetMapping("/api/items/{id}")
// public Item getItem(@PathVariable Long id) { return new Item(id, "Test Item"); }
// }
// class Item { public Long itemId; public String name; public Item(Long itemId, String name) { this.itemId = itemId; this.name = name; } }
What is the default scope for beans in Spring and Spring Boot applications?
What is the output of this code snippet, assuming `Product` with `name='Widget A'` and `name='Widget B'` exists, but `name='Gadget'` does not?
java
import jakarta.persistence.criteria.Predicate;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.util.List;
// Assuming Product entity has a 'name' field
interface ProductRepository extends JpaRepository<Product, Long>, JpaSpecificationExecutor<Product> {}
// Assuming Product and ProductRepository are properly defined and wired
// and 'productRepository' is an injected instance.
// Simulate DB content: Product(id=1, name='Widget A'), Product(id=2, name='Widget B')
public class TestService {
ProductRepository productRepository;
public TestService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
public int countProducts(String nameContains) {
Specification<Product> spec = (root, query, cb) -> {
return cb.like(root.get("name"), "%" + nameContains + "%");
};
List<Product> products = productRepository.findAll(spec);
return products.size();
}
}
// In a conceptual main method or test:
// System.out.println(new TestService(productRepositoryMock).countProducts("Widget"));
What is the output of this code snippet, assuming `userRepository` contains a `User` with `id=1` and `email="jane@example.com"` initially?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
// Assume UserRepository and User entity exist
@RestController
@RequestMapping("/api/users")
public class UserController {
private UserRepository userRepository;
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User userDetails) {
return userRepository.findById(id)
.map(user -> {
user.setEmail(userDetails.getEmail());
return ResponseEntity.ok(userRepository.save(user));
})
.orElseGet(() -> ResponseEntity.notFound().build());
}
}
// Simulate an HTTP PUT request to /api/users/1 with body { "email": "jane.doe@example.com" }
// What would be the HTTP Status and the response body's user email?