🌱 Spring Boot MCQ Questions – Page 18

Questions 341–360 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q341 medium
After successfully creating a new resource via a POST request, it is good practice to include a `Location` header in the response, pointing to the URI of the newly created resource. Which Spring class is commonly used with `ResponseEntity` to construct this URI programmatically?
Q342 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;

@SpringBootApplication
public class App4 {
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(App4.class, args);
        try {
            ctx.getBean("nonExistentBean");
        } catch (Exception e) {
            System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage().split("\n")[0]);
        }
    }
}
Q343 medium code error
What error will occur when Spring attempts to create a bean for the `MyService` interface annotated with `@Component`?
java
import org.springframework.stereotype.Component;

@Component
public interface MyService {
    void doSomething();
}
Q344 medium code output
What is the output of this code when accessing '/api/process'?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;

class SpecificLogicException extends RuntimeException {
    public SpecificLogicException(String msg) { super(msg); }
}

@ControllerAdvice
public class GlobalHandler {
    @ExceptionHandler(SpecificLogicException.class)
    @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
    public String handleSpecificLogic(SpecificLogicException ex) {
        return "Processing Failed: " + ex.getMessage();
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String handleGenericRuntime(RuntimeException ex) {
        return "Generic Error: " + ex.getMessage();
    }
}

@RestController
public class ServiceController {
    @GetMapping("/api/process")
    public String process() {
        throw new SpecificLogicException("Validation error");
    }
}
Q345 medium
If you have multiple beans of the same type and want to designate one of them as the default candidate for autowiring without using `@Qualifier` every time, which annotation would you use on the preferred bean definition?
Q346 medium
In Spring Boot, what is the core component responsible for managing the lifecycle and dependencies of application objects (beans)?
Q347 medium code output
What is the output after saving an `Order` entity which contains an `@Embedded` `Address` object?
java
import jakarta.persistence.*;

@Embeddable
public class Address {
    private String street;
    private String city;
    // constructors, getters
    public Address(String street, String city) { this.street = street; this.city = city; }
}

@Entity(name = "OrderEntity") // Renamed to avoid clash with Java's Order
public class OrderEntity {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
    private String orderNumber;
    @Embedded private Address shippingAddress;
    // constructors, getters
    public OrderEntity() {}
    public OrderEntity(String orderNumber, Address shippingAddress) { this.orderNumber = orderNumber; this.shippingAddress = shippingAddress; }
}

// Assume orderRepository is injected and available
// Assume transaction context is active
OrderEntity order = new OrderEntity("ORD-001", new Address("123 Main St", "Anytown"));
orderRepository.save(order);
System.out.println("Order saved. ID: " + order.getId() + ", Shipping City: " + order.getShippingAddress().getCity());
Q348 medium
How do you extract a variable directly from the URI path (e.g., `/products/{id}`) into a method parameter in a Spring Boot GET request handler?
Q349 medium code output
A Spring Boot application with `@EnableScheduling` has the following component. What is the approximate output after 7-8 seconds of the application running, assuming default single-threaded task execution? Assume the application starts at T=0, and timestamps are for illustrative purposes.
java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ConcurrencyScheduler {

    @Scheduled(fixedRate = 2000) // Task A
    public void taskA() throws InterruptedException {
        System.out.println(System.currentTimeMillis() + " - Task A started.");
        Thread.sleep(3000); // Simulate long work
        System.out.println(System.currentTimeMillis() + " - Task A finished.");
    }

    @Scheduled(fixedRate = 1000) // Task B
    public void taskB() {
        System.out.println(System.currentTimeMillis() + " - Task B executed.");
    }
}
Q350 medium
What happens if a `@RequestParam` is defined to expect an `int` but receives a non-numeric string (e.g., 'abc') from the request?
Q351 medium code output
What is the HTTP response body when a GET request is made to `/payments/abc-123`?
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 PaymentController {
    @GetMapping("/payments/{transactionId}")
    public String getTransactionStatus(@PathVariable Long transactionId) {
        return "Transaction Status: " + transactionId;
    }
}
Q352 medium
When a Spring Boot `@RestController` method returns a plain Java object (POJO) in response to a GET request, what is the default content type that the framework typically serializes the response into?
Q353 medium code error
When a POST request is sent to `/api/users` with a JSON body `{"name": "ab"}`, what will be the default behavior if no `@ExceptionHandler` is configured?
java
import jakarta.validation.Valid;
import jakarta.validation.constraints.Size;
import org.springframework.web.bind.annotation.*;

@RestController
public class MyController {

    @PostMapping("/api/users")
    public String createUser(@Valid @RequestBody UserDto user) {
        return "User created: " + user.getName();
    }

    static class UserDto {
        @Size(min = 3)
        private String name;
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
    }
}
Q354 medium code error
What error occurs if a client sends a POST request to `/id` with `Content-Type: application/json` and an empty JSON object `{}` as the body?
java
package com.example.demo;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

@RestController
public class IdController {
    @PostMapping("/id")
    public ResponseEntity<String> processId(@RequestBody Integer id) {
        return ResponseEntity.ok("Received ID: " + id);
    }
}
Q355 medium code output
Consider the following Spring Boot application. What will be the output when executed?
java
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;

@Component
class DataSourceConfig {
    public String getConnectionUrl() {
        return "jdbc:h2:mem:testdb";
    }
}

class ConnectionManager {
    private final String url;
    public ConnectionManager(String url) {
        this.url = url;
        System.out.println("ConnectionManager created with URL: " + url);
    }
}

@Configuration
class AppConfig {
    @Bean
    public ConnectionManager connectionManager(DataSourceConfig dataSourceConfig) {
        return new ConnectionManager(dataSourceConfig.getConnectionUrl());
    }
}

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        var context = SpringApplication.run(MyApplication.class, args);
        ConnectionManager manager = context.getBean(ConnectionManager.class);
    }
}
Q356 medium code output
What is the output of this Spring Boot code snippet?
java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class CalculationService {
    @Value("#{10 * 3 + 2}")
    private int result;

    public int getResult() {
        return result;
    }
}
// In a Spring Boot application, if this component is scanned:
// CalculationService service = applicationContext.getBean(CalculationService.class);
// System.out.println(service.getResult());
Q357 medium code output
Assume there is a `@RestController` with a `/data` endpoint returning "Controller: Service Data" (from an injected service). What does this code print to the console when `testDataEndpoint` is executed?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.junit.jupiter.api.Test;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class RandomPortTest {

    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    void testDataEndpoint() {
        String url = "http://localhost:" + port + "/data";
        String response = restTemplate.getForObject(url, String.class);
        System.out.println(response);
    }
}
Q358 medium code output
What is the HTTP status returned by the `processXmlData` method when a POST request is made to `/data` with `Content-Type: application/json` and the body `{"key": "value"}`?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

@RestController
@RequestMapping("/data")
class DataController {
    @PostMapping(consumes = MediaType.APPLICATION_XML_VALUE)
    public ResponseEntity<String> processXmlData(@RequestBody String xmlData) {
        return new ResponseEntity<>("XML Data processed: " + xmlData.length() + " chars", HttpStatus.OK);
    }
}
Q359 medium
What is the primary purpose of the `@RestController` annotation in Spring Boot?
Q360 medium
What is the primary function of the `@RequestBody` annotation in a Spring Boot REST controller method?
← Prev 1617181920 Next → Page 18 of 49 · 971 questions