🌱 Spring Boot MCQ Questions – Page 15

Questions 281–300 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q281 medium
For a REST endpoint in a `@RestController` that successfully processes a request but has no specific data to return, what is an appropriate return type that allows control over the HTTP status code?
Q282 medium code output
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

class ConfiguredBean { public String getType() { return "Configured Bean"; } }

@Configuration
class AppConfig { @Bean public ConfiguredBean myBean() { return new ConfiguredBean(); } }

@SpringBootApplication
public class App2 {
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(App2.class, args);
        ConfiguredBean bean = ctx.getBean(ConfiguredBean.class);
        System.out.println(bean.getType());
    }
}
Q283 medium code output
What is the output printed to the console when the following Spring Boot `@Service` and its usage in a `CommandLineRunner` are executed? (Assume standard Spring Boot application setup and necessary imports for `org.springframework.stereotype.Service`.)
java
import org.springframework.stereotype.Service;

@Service
class SimpleMessageService {
    public String getMessage() {
        return "Hello from @Service!";
    }
}

// In a @SpringBootApplication's CommandLineRunner, after autowiring:
// System.out.println(simpleMessageService.getMessage());
Q284 medium code output
What is the HTTP status code returned by the following Spring Boot controller method if a DELETE request is sent to `/api/data/10` and `dataService.softDelete(10L)` successfully marks the data as deleted without physically removing it from the database?
java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/data")
public class DataController {

    private DataService dataService;

    // Constructor injected dataService

    @DeleteMapping("/{id}")
    public ResponseEntity<String> softDeleteData(@PathVariable Long id) {
        dataService.softDelete(id);
        return new ResponseEntity<>("Data marked as deleted.", HttpStatus.ACCEPTED);
    }
}
Q285 medium code output
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);
        MyComponent component = context.getBean("specialComponent", MyComponent.class);
        System.out.println(component.getName());
    }
}

class MyComponent {
    private String name;
    public MyComponent(String name) { this.name = name; }
    public String getName() { return name; }
}

@Configuration
class AppConfig {
    @Bean(name = {"myComponent", "specialComponent"})
    public MyComponent createComponent() {
        return new MyComponent("Initialized via @Bean");
    }
}
Q286 medium code error
Given an `Item` DTO that *only* has a parameterized constructor `public Item(String name)`, and no default constructor. What error occurs when a client sends `{"name": "Laptop"}` with `Content-Type: application/json`?
java
package com.example.demo;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

public class Item {
    private String name;
    public Item(String name) { this.name = name; }
    public String getName() { return name; }
}

@RestController
public class ItemController {
    @PostMapping("/items")
    public ResponseEntity<String> createItem(@RequestBody Item item) {
        return ResponseEntity.ok("Item created: " + item.getName());
    }
}
Q287 medium code output
If a request with `Host: example.com` and `User-Agent: Mozilla` arrives at the gateway, which URI will it be routed to?
java
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GatewayConfig {
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("host_route", r -> r.host("example.com")
                        .uri("http://localhost:8081"))
                .route("agent_route", r -> r.header("User-Agent", ".*Mozilla.*")
                        .uri("http://localhost:8082"))
                .build();
    }
}
Q288 medium code error
If `productService.deleteProduct(id)` throws a `ProductNotFoundException` (a custom runtime exception), what HTTP status will this endpoint return?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    private ProductService productService; // Assume injected

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
        try {
            productService.deleteProduct(id);
            return ResponseEntity.noContent().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
}
Q289 medium
Which `@RequestMapping` attribute is used to specify that a controller method should only handle HTTP POST requests?
Q290 medium
Which of the following best describes how Spring Boot primarily implements Inversion of Control?
Q291 medium
You have an optional dependency that might not always be present in the `ApplicationContext`. How can you configure `@Autowired` to prevent an error if the dependency is not found?
Q292 medium code error
A client sends a DELETE request to `/api/orders/123`. What error will this code produce?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    private OrderService orderService; // Assume injected

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteOrder(@RequestParam("id") Long orderId) {
        orderService.deleteOrder(orderId);
        return ResponseEntity.noContent().build();
    }
}
Q293 medium code error
Consider the following Spring Boot application setup. What error will occur when this application attempts to start?
java
package com.example.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

class MyDependency {
    public String getData() {
        return "Data from dep";
    }
}

@Component
class MyService {
    private final MyDependency dependency;

    @Autowired
    public MyService(MyDependency dependency) {
        this.dependency = dependency;
    }
}

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
Q294 medium code error
What is the result when Spring Boot attempts to start this application?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
class MyDataProcessor {
    @Autowired
    private List<String> stringList;

    public void process() {
        // Uses stringList
    }
}
Q295 medium code output
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.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component @Scope("prototype")
class ScopedBean {
    private static int counter = 0;
    public ScopedBean() { counter++; }
    public int getInstanceCount() { return counter; }
}

@SpringBootApplication
public class App8 {
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(App8.class, args);
        ScopedBean b1 = ctx.getBean(ScopedBean.class);
        ScopedBean b2 = ctx.getBean(ScopedBean.class);
        System.out.println(b1.getInstanceCount() + "," + b2.getInstanceCount());
    }
}
Q296 medium code error
Given the Spring Boot application structure below, what error will occur when running the `main` method and trying to retrieve `externalMessage`?
java
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ExternalConfig {
    @Bean
    public String externalMessage() {
        return "Hello from external config!";
    }
}

// In a separate package: com.example.app
package com.example.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication // Assumes base package is com.example.app
public class MyApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(MyApplication.class, args);
        String message = context.getBean("externalMessage", String.class); 
        System.out.println(message);
    }
}
Q297 medium code output
Given `application.properties` contains `app.greeting=Hello Spring!` 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 GreetingService {
    @Value("${app.greeting}")
    private String greetingMessage;

    public String getGreeting() {
        return greetingMessage;
    }
}
// In a Spring Boot application, if this component is scanned:
// GreetingService service = applicationContext.getBean(GreetingService.class);
// System.out.println(service.getGreeting());
Q298 medium code error
Given the following Spring Boot configuration, what is the consequence when `ReportGenerator` attempts to use `DataSourceManager`?
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Autowired;

@Configuration
public class AppConfig {

    @Bean
    public DataSourceManager dataSourceManager() {
        return null; // Explicitly returning null
    }

    @Bean
    public ReportGenerator reportGenerator(@Autowired DataSourceManager dsm) {
        return new ReportGenerator(dsm);
    }
}

class DataSourceManager {}
class ReportGenerator {
    public ReportGenerator(DataSourceManager dsm) {}
}
Q299 medium code error
What error will occur when accessing `/api/items?page=abc&size=10` with the following Spring Boot controller?
java
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class ItemController {

    @GetMapping("/items")
    public String getItems(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam int size) {
        return "Fetching items - Page: " + page + ", Size: " + size;
    }
}
Q300 medium code output
What is the HTTP status and body returned by the `processPayload` method when a POST request is made to `/payload` with `Content-Type: application/json` and the JSON body `{"id": "not-an-int"}`?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;

class DataPayload {
    private int id;
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
}

@RestController
@RequestMapping("/payload")
class PayloadController {
    @PostMapping
    public ResponseEntity<String> processPayload(@RequestBody DataPayload payload) {
        return new ResponseEntity<>("Processed ID: " + payload.getId(), HttpStatus.OK);
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<String> handleHttpMessageNotReadable(HttpMessageNotReadableException ex) {
        return new ResponseEntity<>("Invalid request body format: " + ex.getMessage().split(":")[0].trim(), HttpStatus.BAD_REQUEST);
    }
}
← Prev 1314151617 Next → Page 15 of 49 · 971 questions