🌱 Spring Boot MCQ Questions – Page 28
Questions 541–560 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsGiven a `MyController` class with a `@GetMapping("/test")` method that returns "Hello from Controller!", what is the output of this test code?
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.status;
@WebMvcTest(controllers = MyController.class)
class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testEndpointReturnsMessage() throws Exception {
this.mockMvc.perform(get("/test"))
.andExpect(status().isOk())
.andDo(result -> System.out.print(result.getResponse().getContentAsString()));
}
}
What does this Spring Boot application print to the console?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
interface NotificationService { String notifyUser(); }
@Component
@Primary
class EmailNotificationService implements NotificationService { @Override public String notifyUser() { return "Sending email notification (Primary)"; } }
@Component("smsNotification")
class SmsNotificationService implements NotificationService { @Override public String notifyUser() { return "Sending SMS notification"; } }
@Component
class AppRunner implements CommandLineRunner {
@Autowired
@Qualifier("smsNotification")
private NotificationService service;
@Override
public void run(String... args) { System.out.println(service.notifyUser()); }
}
@SpringBootApplication
class App {}
What error will occur when this Spring Boot application attempts to start?
java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/api/hello")
public String helloWorld() {
return "Hello from GET!";
}
@GetMapping("/api/hello")
public String greetUser() {
return "Greetings!";
}
}
What is the output of this code?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
class MyLifecycleBean {
private String state = "INIT";
public MyLifecycleBean() { System.out.println("1: " + state); }
@PostConstruct
public void postConstruct() { state = "POST_CONSTRUCT"; System.out.println("2: " + state); }
public String getState() { return state; }
}
@SpringBootApplication
public class App9 {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(App9.class, args);
MyLifecycleBean bean = ctx.getBean(MyLifecycleBean.class);
System.out.println("3: " + bean.getState());
}
}
Consider the following Spring Boot controller method signature: `@GetMapping("/users/{userId}/posts/{postId}") public String getUserPost(@PathVariable String userId, @PathVariable String postId)`. How are `userId` and `postId` values extracted?
Given the Spring Boot application, what will be the output?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
interface DataProcessor { String process(); }
class SimpleProcessor implements DataProcessor { private String name; public SimpleProcessor(String name) { this.name = name; } @Override public String process() { return "Processing with " + name; } }
@Configuration
class AppConfig {
@Bean(name = "fastProcessor")
public DataProcessor fastProcessor() { return new SimpleProcessor("FastProcessor"); }
@Bean(name = "slowProcessor")
public DataProcessor slowProcessor() { return new SimpleProcessor("SlowProcessor"); }
}
@Component
class DataRunner implements CommandLineRunner {
@Autowired
@Qualifier("slowProcessor")
private DataProcessor processor;
@Override
public void run(String... args) { System.out.println(processor.process()); }
}
@SpringBootApplication
class App {}
What is the expected error when accessing this endpoint with GET /report?
java
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
class CustomReport { // Missing getters/setters and default constructor for serialization
String name = "Test";
public CustomReport(String name) { this.name = name; }
}
@RestController
public class ReportController {
@GetMapping("/report")
public CustomReport getReport() {
return new CustomReport("Monthly");
}
}
Given the `User` and `Address` classes below, what will be the value of `user.getAddress().getStreet()` if a form is submitted with data 'name=Charlie&address.street=Oak Ave&address.city=Springfield'?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
// Address.java
public class Address {
private String street; private String city;
public String getStreet() { return street; }
public void setStreet(String street) { this.street = street; }
public String getCity() { return city; }
public void setCity(String city) { this.city = city; }
}
// User.java
public class User {
private String name; private Address address;
public User() { this.address = new Address(); } // Important for nested binding
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Address getAddress() { return address; }
public void setAddress(Address address) { this.address = address; }
}
@Controller
public class NestedFormController {
@PostMapping("/user/update")
public String updateUser(@ModelAttribute User user) {
// user object is processed here
return "profile";
}
}
How do you typically add data that needs to be displayed in a view template (e.g., Thymeleaf, JSP) from within a `@Controller` method?
What is the primary concept behind Inversion of Control (IoC) in Spring Boot applications?
What error occurs when accessing `/files/document.pdf` with the following controller?
java
import org.springframework.web.bind.annotation.*;
@RestController
public class FileController {
@GetMapping("/files/{filename:[a-zA-Z]+\.txt}")
public String downloadFile(@PathVariable String filename) {
return "Downloading: " + filename;
}
}
Given the `BookController` below, what will be the HTTP status and body if a DELETE request is made to `/api/books/purge` and `bookService.deleteAllBooks()` successfully empties the entire book collection?
java
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/books")
public class BookController {
private BookService bookService;
// Constructor injected bookService
@DeleteMapping("/purge")
@ResponseStatus(HttpStatus.OK)
public String purgeBooks() {
bookService.deleteAllBooks();
return "All books have been purged.";
}
}
What is the expected outcome when Spring Boot attempts to initialize the application context with this configuration?
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfig {
@Bean
public String nullStringBean() {
return null;
}
}
Based on the Spring Boot code, what will be the HTTP status code and response body when a GET request is made to `/process/null`?
java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
class ProcessController {
@GetMapping("/process/null")
public String processNull() {
String data = null;
return data.toLowerCase(); // Throws NullPointerException
}
}
@RestControllerAdvice
class GenericErrorHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleAllExceptions(Exception ex) {
return new ResponseEntity<>("An unexpected error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
What is the HTTP status code and response body returned by this Spring Boot controller method?
java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/status")
public ResponseEntity<Integer> getCustomStatus() {
return new ResponseEntity<>(123, HttpStatus.ACCEPTED);
}
}
What happens if you have multiple classes annotated with `@SpringBootApplication` in a single Spring Boot project?
Consider the following controller method. If `myTemplate.html` attempts to access `${myObject.data}` after `/display` is requested, what is the error?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;
class MyData {
public String info = "Hello";
}
@Controller
public class MyObjectController {
@GetMapping("/display")
public String displayPage(Model model) {
model.addAttribute("myObject", new MyData());
// The template myTemplate.html has th:text="${myObject.data}"
return "myTemplate";
}
}
Consider the following Spring Boot controller method. What HTTP status code and body would be returned if a DELETE request is made to `/api/users/456` and the user is successfully deleted?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
private UserService userService;
// Constructor injected userService
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return ResponseEntity.noContent().build();
}
}
Observe the Spring Boot application below. What will be the exact sequence of outputs printed to the console?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Lazy;
@Component
class EagerService {
public EagerService() {
System.out.println("EagerService initialized.");
}
public String getStatus() { return "Eager service ready"; }
}
@Lazy
@Component
class LazyService {
public LazyService() {
System.out.println("LazyService initialized.");
}
public String getStatus() { return "Lazy service ready"; }
}
@Component
class MyRunner {
private final EagerService eagerService;
private final LazyService lazyService;
@Autowired
public MyRunner(EagerService eagerService, LazyService lazyService) {
this.eagerService = eagerService;
this.lazyService = lazyService;
System.out.println("MyRunner created.");
}
public void run() {
System.out.println(eagerService.getStatus());
System.out.println(lazyService.getStatus());
}
}
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
var context = SpringApplication.run(MyApplication.class, args);
MyRunner runner = context.getBean(MyRunner.class);
runner.run();
}
}
What is the output when accessing `/welcome?name=Alice`?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@RestController
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
@GetMapping("/welcome")
public String welcomeUser(@RequestParam(defaultValue = "Guest") String name) {
return "Welcome, " + name + "!";
}
}