🌱 Spring Boot MCQ Questions – Page 23
Questions 441–460 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsWhat is the primary purpose of the `@EnableAutoConfiguration` annotation, which is implicitly included in `@SpringBootApplication`?
What is the output when accessing `/calculate?num1=10&num2=invalid`?
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("/calculate")
public String calculate(@RequestParam int num1, @RequestParam int num2) {
return "Sum: " + (num1 + num2);
}
}
How can a Spring Boot controller method receive multiple values for a single request parameter name (e.g., `colors=red&colors=blue`)?
What is the printed output of this code?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
@Component("myCustomBeanName") // Explicit bean name
class NamedComponent {
public String getName() { return "Named Component"; }
}
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
var context = SpringApplication.run(DemoApplication.class, args);
var component = context.getBean("myCustomBeanName", NamedComponent.class);
System.out.println(component.getName());
}
}
Which component of `@SpringBootApplication` is primarily responsible for ensuring that `@Service`, `@Repository`, and `@Controller` annotated classes are found and registered as beans?
To retrieve a value from the URL's query string (e.g., `GET /items?name=laptop`) using `@RequestMapping`, which parameter annotation would typically be used in the method signature?
To ensure a handler method only processes requests that include a specific HTTP header (e.g., `X-API-Version=1`), which attribute of `@RequestMapping` would you use?
If a client sends a plain text body like "MyReport" with `Content-Type: text/plain` to this endpoint, what will be the HTTP error returned by Spring Boot?
java
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/reports")
public class ReportController {
@PostMapping
public String generateReport(@RequestBody ReportData data) {
return "Report generated for type: " + data.getType();
}
}
class ReportData {
private String type;
public String getType() { return type; }
public void setType(String type) { this.type = type; }
}
What will be printed when this Spring Boot application runs?
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;
import org.springframework.stereotype.Component;
@Configuration
class StringConfig {
@Bean
@Qualifier("welcomeMsg")
public String greeting() { return "Hello, Spring Boot!"; }
@Bean
@Qualifier("farewellMsg")
public String goodbye() { return "Goodbye, Spring Boot!"; }
}
@Component
class StringPrinter implements CommandLineRunner {
@Autowired
@Qualifier("welcomeMsg")
private String message;
@Override
public void run(String... args) { System.out.println(message); }
}
@SpringBootApplication
class App {}
What error will occur when the Spring context initializes `MyClient`?
java
import org.springframework.stereotype.Component;
class ExternalApiConnector {
public ExternalApiConnector() {}
public void connect() { System.out.println("Connecting..."); }
}
@Component
public class MyClient {
private final ExternalApiConnector connector;
public MyClient(ExternalApiConnector connector) {
this.connector = connector;
}
}
Assume there is a `ConfigComponent` class that injects a property `@Value("${app.message:Default Message}")`. What does this code print to the console when `testPropertyOverride` is executed?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.jupiter.api.Test;
// ConfigComponent (not shown) injects @Value("${app.message:Default Message}")
@SpringBootTest(properties = {"app.message=Test Override Message"})
public class PropertyOverrideTest {
@Autowired
private ConfigComponent configComponent;
@Test
void testPropertyOverride() {
System.out.println(configComponent.getMessage());
}
}
Given the following Spring Boot controller method for displaying a form and a Thymeleaf template (`productForm.html`) that uses `th:object="${productForm}"`, what error will occur when `/showProductForm` is accessed?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
public class ProductForm {
private String name;
private double price;
// Getters and Setters, default constructor...
}
@Controller
public class ProductController {
@GetMapping("/showProductForm")
public String showProductForm() {
return "productForm";
}
}
Given the `EventDto` and controller, what is the return value of `createEvent` if the POST request body is `{"title":"Meeting", "eventTime":"2024-07-20T10:30:00"}`?
java
import org.springframework.web.bind.annotation.*;
import lombok.Data;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Data
class EventDto {
private String title;
private LocalDateTime eventTime;
}
@RestController
@RequestMapping("/events")
public class EventController {
@PostMapping
public String createEvent(@RequestBody EventDto eventDto) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
return "Event: " + eventDto.getTitle() + " at " + eventDto.getEventTime().format(formatter);
}
}
What error will occur when compiling the following Spring Boot code?
java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
public class ResponseBuilderTest {
public ResponseEntity<String> createResponse() {
return ResponseEntity.status(HttpStatus.OK).header("X-Custom", "value").build("Body Content");
}
}
What error occurs during Spring Boot application startup?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Optional;
interface MyDependency {}
@Component
class MyDependencyImplA implements MyDependency {}
@Component
class MyDependencyImplB implements MyDependency {}
@Component
class MyConsumer {
@Autowired(required = false)
private MyDependency dependency;
}
How can a specific HTTP request header (e.g., `User-Agent` or `Authorization`) be accessed and bound to a method parameter in a Spring Boot GET controller method?
What error will occur during application startup for the following component and configuration?
java
java
@Component
public class NetworkConfig {
@Value("${network.port:invalid}")
private int port;
public int getPort() {
return port;
}
}
properties
# application.properties (file does NOT contain 'network.port')
How would you add a custom header named 'X-Request-ID' with the value '12345' to a `ResponseEntity` that returns an HTTP 200 OK status with data?
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;
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(MyApp.class, args);
MessageService service = context.getBean(MessageService.class);
System.out.println(service.getMessage());
}
}
interface MessageService { String getMessage(); }
class EmailService implements MessageService {
@Override
public String getMessage() { return "Sending email..."; }
}
@Configuration
class AppConfig {
@Bean
public MessageService emailService() { // Returns interface type
return new EmailService();
}
}
What is the console output when a GET request is made to `/error` in this setup?
java
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
class ErrorInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
System.out.println("ErrorInterceptor: preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { /* Not called if exception occurs */ }
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
System.out.println("ErrorInterceptor: afterCompletion - Exception: " + (ex != null ? ex.getMessage() : "None"));
}
}
@Configuration
class ErrorWebConfig implements WebMvcConfigurer {
private final ErrorInterceptor interceptor;
public ErrorWebConfig(ErrorInterceptor interceptor) { this.interceptor = interceptor; }
@Override
public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(interceptor).addPathPatterns("/error"); }
}
@RestController
class ErrorController {
@GetMapping("/error")
public String simulateError() {
System.out.println("Controller: Throwing exception");
throw new RuntimeException("Simulated error");
}
}