🌱 Spring Boot MCQ Questions – Page 9
Questions 161–180 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsBeyond managing beans, `ApplicationContext` also provides generic resource loading capabilities. Which prefix typically indicates a resource that should be loaded from the classpath?
Consider a `UserRegistrationForm` with a `@NotNull` constraint on `username`. If the following controller method is used to process a form submission where `username` is submitted as empty, what error will occur when the method attempts to use the `username`?
java
import jakarta.validation.constraints.NotNull;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
public class UserRegistrationForm {
@NotNull(message = "Username cannot be null")
private String username;
// Getters and Setters, default constructor...
}
@Controller
public class RegistrationController {
@PostMapping("/register")
public String registerUser(@ModelAttribute UserRegistrationForm form) {
// Assume form.username is null from invalid submission without @Valid
return "welcome/" + form.getUsername().toLowerCase();
}
}
What content type is asserted to be present in the response?
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.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
@WebMvcTest(controllers = TestController.class)
class TestControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testPostEndpoint() throws Exception {
mockMvc.perform(post("/api/data")
.contentType(MediaType.APPLICATION_JSON)
.content("{"name":"Test"}"))
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
}
// Assuming TestController has:
// @RestController
// class TestController {
// @PostMapping("/api/data")
// public String processData(@RequestBody String data) { return data; }
// }
What kind of error will occur during the Spring Boot application startup with the following `RestController`?
java
import org.springframework.web.bind.annotation.*;
@RestController
public class MyController {
@GetMapping("/users")
public String getAllUsers() {
return "All users";
}
@GetMapping("/users")
public String getSingleUser() {
return "Single user";
}
}
If a Spring Boot controller adds an attribute `user` to the `Model` like `model.addAttribute("user", userObject);`, how would you typically access this `user` object within a Thymeleaf template?
If a GET request handler method in a Spring Boot `@RestController` needs to ensure its response is always of a specific media type, such as `application/xml`, which attribute of `@GetMapping` would you use?
What is the output of this code when a POST request is made to '/data' with an empty body?
java
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DataController {
@RequestMapping(value = "/data", method = RequestMethod.POST)
public String receiveData() {
return "POST Data Received.";
}
@RequestMapping(value = "/data", method = RequestMethod.GET)
public String getData() {
return "GET Data Requested.";
}
}
What is the output of this code?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
interface GreetingService { String greet(); }
@Component("englishGreeting") static class EnglishGreetingService implements GreetingService { @Override public String greet() { return "Hello"; } }
@Primary @Component("spanishGreeting") static class SpanishGreetingService implements GreetingService { @Override public String greet() { return "Hola"; } }
@SpringBootApplication
public class MyApplication {
@Autowired private GreetingService greetingService;
public static void main(String[] args) {
MyApplication app = SpringApplication.run(MyApplication.class, args).getBean(MyApplication.class);
System.out.println(app.greetingService.greet());
}
}
What is the expected HTTP response if a DELETE request is made to `/api/files/cleanup` and the `fileService.cleanupOldFiles()` method returns `true`?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/api/files")
public class FileController {
private FileService fileService;
// Constructor injected fileService
@DeleteMapping("/cleanup")
public ResponseEntity<Map<String, Boolean>> cleanupFiles() {
boolean cleaned = fileService.cleanupOldFiles();
return ResponseEntity.ok(Map.of("success", cleaned));
}
}
Given `application.properties` contains `api.host=example.com` and `api.path=/users` and the following Java code, what does it print?
java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class UrlBuilder {
@Value("http://${api.host}${api.path}")
private String fullUrl;
public String getFullUrl() {
return fullUrl;
}
}
// In a Spring Boot application, if this component is scanned:
// UrlBuilder builder = applicationContext.getBean(UrlBuilder.class);
// System.out.println(builder.getFullUrl());
What is the primary benefit of creating a custom qualifier annotation (e.g., `@FastProcessor`) instead of directly using `@Qualifier("fastProcessor")`?
Given the `User` class (with `id` and `name` properties) below, what is the HTTP response body when a GET request is made to '/api/user'?
java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
// Assuming User class is defined as: class User { private Long id; private String name; public User(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public String getName() { return name; } }
@RestController
public class UserController {
@GetMapping("/api/user")
public User getUser() {
return new User(101L, "Jane Doe");
}
}
How would you use `@Value` to inject the value of the `user.home` system property?
A form-backing object `OrderForm` has a field of a custom type `Address`. If the HTML form includes `<input type="text" name="shippingAddress">` where `shippingAddress` is intended to bind to `OrderForm.address`, which error is most likely to occur without a custom converter?
java
public class Address {
private String street;
private String city;
// Getters and Setters, constructor...
}
public class OrderForm {
private Address address;
// Getters and Setters...
}
@Controller
public class OrderController {
@PostMapping("/order")
public String processOrder(@ModelAttribute OrderForm orderForm) {
// Logic to save order
return "orderConfirmation";
}
}
What is the HTTP response body when a GET request is made to `/reports/daily`?
java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ReportController {
@GetMapping("/reports/{reportName:[a-z]+}")
public String getReport(@PathVariable("reportName") String name) {
return "Fetching report: " + name.toUpperCase();
}
}
What error will the ApplicationContext report during initialization given the following classes?
java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@Component
class ServiceA {
@Autowired
public ServiceA(ServiceB b) {}
}
@Component
class ServiceB {
@Autowired
public ServiceB(ServiceA a) {}
}
public class CircularApp {
public static void main(String[] args) {
new AnnotationConfigApplicationContext(CircularApp.class.getPackage().getName());
}
}
What is the HTTP response body when accessing `/users/101` with the following controller?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserController {
@GetMapping("/users/{userId}")
@ResponseBody
public String getUserById(@PathVariable long userId) {
return "User ID: " + userId;
}
}
What is the HTTP status code and response body returned by this Spring Boot controller method?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@RestController
public class MyController {
@GetMapping("/optional")
public ResponseEntity<String> getOptionalData() {
Optional<String> data = Optional.empty(); // Represents no data found
return data.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}
}
When Spring performs autowiring for a field, which of the following is true?
What error will prevent this code from compiling?
java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
class MyConstants {
public static String JSON_TYPE = "application/json";
}
@RestController
public class MyController {
@GetMapping(value = "/data", produces = MyConstants.JSON_TYPE)
public String getData() {
return "{ \"key\": \"value\" }";
}
}