What will be the outcome when running this Spring Boot application?
java
public interface Printer {
String print();
}
@Configuration
public class AppConfig {
@Bean
public Printer inkjetPrinter() { // Bean named "inkjetPrinter" by default
return () -> "Printing with Inkjet";
}
}
@Component
public class PrintManager {
@Autowired
@Qualifier("laserPrinter") // No bean named "laserPrinter"
private Printer printer;
public void managePrint() {
System.out.println(printer.print());
}
}
✅ Correct Answer: B) org.springframework.beans.factory.NoSuchBeanDefinitionException
The `@Bean` method `inkjetPrinter()` creates a bean named `inkjetPrinter` by default. The `@Qualifier("laserPrinter")` attempts to find a bean with a different name, which doesn't exist, resulting in a `NoSuchBeanDefinitionException`.
Q882medium
Which Spring Boot annotation is used to map an HTTP POST request to a specific handler method in a REST controller?
✅ Correct Answer: C) @PostMapping
@PostMapping is a convenience annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST), specifically designed for handling HTTP POST requests.
Q883mediumcode output
Given the Spring Boot controller above, what will be the HTTP response body (or behavior) when a GET request is made to `/item/invalid-id`?
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 ItemController {
@GetMapping("/item/{itemId}")
public String getItem(@PathVariable int itemId) {
return "Retrieved item " + itemId;
}
}
✅ Correct Answer: A) HTTP Status 400 Bad Request (Type Mismatch)
Spring Boot attempts to convert the `itemId` path variable to an `int`. Since "invalid-id" cannot be converted to an integer, it results in a `MethodArgumentTypeMismatchException`, which Spring handles by returning a 400 Bad Request status.
Q884mediumcode output
What is the HTTP response body when a GET request is made to `/items/AXB123`?
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 ItemController {
@GetMapping("/items/{sku}")
public String getItemDetails(@PathVariable("sku") String productIdentifier) {
return "Item SKU: " + productIdentifier;
}
}
✅ Correct Answer: A) Item SKU: AXB123
The `@PathVariable("sku")` explicitly maps the `sku` segment from the URI path to the `productIdentifier` method parameter, allowing different names between the path variable and the method parameter.
Q885mediumcode error
What kind of error will occur when a client attempts to send a JSON request body `{"customerName": "Alice", "quantity": 2}` to this POST endpoint?
java
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/orders")
public class OrderController {
@PostMapping
public String placeOrder(@RequestParam("order") OrderDto order) {
return "Order received for: " + order.getCustomerName();
}
}
class OrderDto {
private String customerName;
private int quantity;
public String getCustomerName() { return customerName; }
public void setCustomerName(String customerName) { this.customerName = customerName; }
public int getQuantity() { return quantity; }
public void setQuantity(int quantity) { this.quantity = quantity; }
}
✅ Correct Answer: A) HTTP 400 Bad Request with a `MissingServletRequestParameterException`.
`@RequestParam` is designed to bind individual parameters from the query string or form data, not to deserialize a complex object from the JSON request body. The server will expect a request parameter named "order" and fail to bind the JSON body, resulting in a 400 error.
Q886medium
Which annotation is used in Spring Boot to extract values from the URI path and bind them to method parameters?
✅ Correct Answer: B) @PathVariable
@PathVariable extracts values directly embedded within the URL path segments, making them integral parts of the resource's identifier.
Q887medium
What happens if a `@RestController` method returns `ModelAndView`?
✅ Correct Answer: B) The `ModelAndView` object itself will be serialized into JSON/XML and returned as the response body.
Since `@RestController` implies `@ResponseBody` on all methods, returning a `ModelAndView` object from a `@RestController` method will cause Spring to attempt to serialize the `ModelAndView` object itself into JSON or XML, rather than using it for view resolution, which is usually not the desired behavior.
Q888medium
What is the primary purpose of the `@Service` annotation in Spring Boot?
✅ Correct Answer: B) To indicate that a class contains business logic and should be managed by the Spring container.
The `@Service` annotation is used to mark a class as a service component in the business layer, typically holding business logic. It's a specialized `@Component`.
Q889medium
How can you inject all beans of a specific interface type (e.g., `PaymentProcessor`) into a `List` using `@Autowired`?
✅ Correct Answer: B) `@Autowired private List<PaymentProcessor> processors;`
Spring can directly autowire all beans of a specified type into a `List` (or `Set`, or `Map` where keys are bean names and values are beans) without requiring additional attributes.
Q890mediumcode error
Consider the following Spring component. What error will occur during application startup?
java
java
@Component
public class IdGenerator {
@Value("#{"".trim()}")
private Long nextId;
public Long getNextId() {
return nextId;
}
}
✅ Correct Answer: A) java.lang.NumberFormatException: For input string: ""
The SpEL expression `"".trim()` evaluates to an empty string. Spring then tries to convert this empty string to a `Long`, which results in a `NumberFormatException` because an empty string cannot be parsed as a number.
Q891mediumcode output
Given the `Product` class with an `ItemType` enum, what will be the value of `product.getItemType()` after a form submission 'productName=Laptop&itemType=ELECTRONICS'?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
// ItemType.java
public enum ItemType {
ELECTRONICS, CLOTHING, BOOKS
}
// Product.java
public class Product {
private String productName; private ItemType itemType;
public String getProductName() { return productName; }
public void setProductName(String productName) { this.productName = productName; }
public ItemType getItemType() { return itemType; }
public void setItemType(ItemType itemType) { this.itemType = itemType; }
}
@Controller
public class ProductController {
@PostMapping("/product/add")
public String addProduct(@ModelAttribute Product product) {
// product object is processed here
return "product_details";
}
}
✅ Correct Answer: A) ItemType.ELECTRONICS
Spring's data binding automatically converts string values from form parameters to enum types if the string matches one of the enum's constants. 'ELECTRONICS' maps directly to ItemType.ELECTRONICS.
Q892medium
When would you typically use the `name` (or `value`) attribute within the `@RequestParam` annotation?
✅ Correct Answer: B) When the method argument name differs from the actual request parameter name.
The `name` (or `value`) attribute is used when the name of the request parameter in the URL does not match the name of the method argument in your controller method.
Q893medium
When the `ApplicationContext` is shutting down, which mechanism allows beans to perform cleanup operations?
✅ Correct Answer: C) The `@PreDestroy` annotation or `destroy()` method of `DisposableBean`
The `@PreDestroy` annotation or implementing the `DisposableBean` interface's `destroy()` method allows beans to execute cleanup logic before the `ApplicationContext` is closed.
Q894mediumcode error
What error will occur when Spring Boot attempts to initialize MyService?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
class UnmanagedDependency {
public String getData() { return "data"; }
}
@Component
class MyService {
@Autowired
private UnmanagedDependency dependency;
public String getInfo() { return dependency.getData(); }
}
✅ Correct Answer: B) org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'UnmanagedDependency' available.
Spring's @Autowired mechanism only works for beans managed by the Spring container. Since 'UnmanagedDependency' is a plain POJO without @Component or other stereotype annotations, Spring cannot find a bean definition for it, leading to a NoSuchBeanDefinitionException during context initialization.
Q895mediumcode error
What is the expected error when accessing this endpoint with GET /hello?
java
import org.springframework.web.bind.annotation.*;
@RestController
public class GreetingController {
@GetMapping("/hello")
public String sayHello(@RequestParam(required = true) String name) {
return "Hello, " + name + "!";
}
}
✅ Correct Answer: A) MissingServletRequestParameterException
Since the @RequestParam 'name' is explicitly marked as required (required=true) and is not provided in the GET /hello request, Spring will throw a MissingServletRequestParameterException, resulting in an HTTP 400 Bad Request error.
Q896mediumcode output
What does this code print to the console when run as a Spring Boot application?
java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@Component
class ServiceB { public ServiceB() { System.out.println("ServiceB created."); } }
@Component
class ClientB implements CommandLineRunner {
private final ServiceB serviceB;
public ClientB(@Autowired ServiceB serviceB) {
this.serviceB = serviceB;
System.out.println("ClientB initialized with ServiceB.");
}
@Override
public void run(String... args) { /* no-op */ }
}
@SpringBootApplication
public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
✅ Correct Answer: A) ServiceB created.
ClientB initialized with ServiceB.
Spring creates `ServiceB` first, printing its constructor message. Then, it injects this instance into `ClientB`'s constructor, printing the `ClientB` initialization message. Spring 4.3+ implicitly infers `@Autowired` on single-constructor components.
Q897mediumcode output
Assuming a Spring Boot application with the following controller, what is the outcome regarding the view and model attributes if a request is made to `/empty`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;
@Controller
public class EmptyController {
@GetMapping("/empty")
public String showEmptyPage(Model model) {
// No attributes are added to the model
return "emptyPage";
}
}
✅ Correct Answer: A) Resolved View Name: emptyPage, Model Attributes: {}
The method explicitly returns the view name 'emptyPage'. Since no attributes are added to the `Model` object, the model passed to the view will be empty. An empty model is valid.
Q898medium
What is the result of `ResponseEntity.ok().build()` when returned from a Spring Boot controller?
✅ Correct Answer: A) An HTTP 200 OK status with an empty response body.
`ResponseEntity.ok()` sets the status to 200 OK, and `build()` without a `body()` call results in a response with no content in the body, which is a valid successful response.
Q899mediumcode output
Given the Spring Boot controller above, what will be the HTTP response body when a GET request is made to `/greeting`?
java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SimpleController {
@GetMapping("/greeting")
public String greet() {
return "Hello from Spring Boot!";
}
}
✅ Correct Answer: A) Hello from Spring Boot!
The `@GetMapping("/greeting")` annotation maps the `/greeting` path to the `greet()` method. The method returns a `String`, which Spring Boot automatically converts into the HTTP response body.
Q900mediumcode error
What kind of error will Spring Boot produce when attempting to instantiate `MyService`?
java
import org.springframework.stereotype.Service;
// MyDependency is NOT a Spring bean
class MyDependency { public String getValue() { return "Dep Value"; } }
@Service
public class MyService {
private MyDependency myDependency;
private String name;
public MyService(MyDependency myDependency) { this.myDependency = myDependency; }
public MyService(String name) { this.name = name; }
public String getResult() { return "Service result"; }
}
✅ Correct Answer: B) A `BeanCreationException` because Spring cannot determine which constructor to use for `MyService` or resolve its dependencies.
With multiple constructors and no explicit `@Autowired` to indicate Spring's preferred choice, Spring will struggle to decide which constructor to use. Furthermore, `MyDependency` is not a Spring-managed bean, making it impossible for Spring to resolve the argument for the first constructor, leading to a `BeanCreationException`.