🌱 Spring Boot MCQ Questions – Page 35

Questions 681–700 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q681 medium code output
What is the HTTP status code and response body for a PUT request to `/api/orders/2` with the JSON body `{"status": "SHIPPED"}`?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.Map;

// Assume Order class has Long id, String status (e.g., "PENDING", "SHIPPED").

@RestController
@RequestMapping("/api/orders")
public class OrderController {
    private Map<Long, Order> orders = new HashMap<>();

    public OrderController() {
        orders.put(1L, new Order(1L, "PENDING"));
        orders.put(2L, new Order(2L, "PROCESSING"));
    }

    @PutMapping("/{id}")
    public ResponseEntity<Order> updateOrderStatus(@PathVariable Long id, @RequestBody Order orderUpdate) {
        if (!orders.containsKey(id)) {
            return ResponseEntity.notFound().build();
        }
        Order existingOrder = orders.get(id);
        if (orderUpdate.getStatus() == null || orderUpdate.getStatus().isEmpty()) {
            return ResponseEntity.badRequest().build(); // Status cannot be empty
        }
        if (existingOrder.getStatus().equals("SHIPPED")) {
            return ResponseEntity.status(409).build(); // Conflict: Cannot modify shipped order
        }
        existingOrder.setStatus(orderUpdate.getStatus());
        orders.put(id, existingOrder);
        return ResponseEntity.ok(existingOrder);
    }
}
Q682 medium code output
What is the console output of this Spring Boot application, demonstrating a custom qualifier?
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.stereotype.Component;
import java.lang.annotation.*;

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
@interface MyCustomQualifier {}

interface ReportingService { String generateReport(); }

@Component
class BasicReportingService implements ReportingService { @Override public String generateReport() { return "Basic Report Generated"; } }

@MyCustomQualifier
@Component
class DetailedReportingService implements ReportingService { @Override public String generateReport() { return "Detailed Report Generated"; } }

@Component
class ReportRunner implements CommandLineRunner {
    @Autowired
    @MyCustomQualifier
    private ReportingService service;

    @Override
    public void run(String... args) { System.out.println(service.generateReport()); }
}

@SpringBootApplication
class App {}
Q683 medium code error
If a client sends a POST request to `/config/timeout` with a request body "3000" (plain text), what will be the value of the `value` parameter in the `updateSetting` method?
java
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/config")
public class ConfigController {
    @PostMapping("/{settingName}")
    public String updateSetting(@PathVariable String settingName, String value) {
        return "Setting " + settingName + " updated to " + value;
    }
}
Q684 medium
What happens if a Spring Boot application attempts to inject a non-existent property `app.nonexistent` using `@Value("${app.nonexistent}")` without specifying a default value?
Q685 medium code output
Consider a Spring Boot application *without* `@EnableScheduling` on its main class, but with the following component. What is the output after 5 seconds of the application running?
java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MissingEnableScheduling {

    @Scheduled(fixedRate = 2000)
    public void importantTask() {
        System.out.println("Important scheduled task running.");
    }
}
Q686 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);
        Processor processor = context.getBean(Processor.class);
        System.out.println(processor.process("input"));
    }
}

class Transformer {
    public String transform(String data) { return "Transformed: " + data.toUpperCase(); }
}

class Processor {
    private Transformer transformer;
    public Processor(Transformer transformer) { this.transformer = transformer; }
    public String process(String data) { return "Processing " + transformer.transform(data); }
}

@Configuration
class AppConfig {
    @Bean
    public Transformer transformer() { return new Transformer(); }

    @Bean
    public Processor processor(Transformer transformer) { // Constructor injection through @Bean parameter
        return new Processor(transformer);
    }
}
Q687 medium
For a form that submits data intended to create a new resource on the server (e.g., registering a new user, adding a new item), which HTTP method should generally be used to submit the form?
Q688 medium code error
Assuming `MyEntityRepository` is a `JpaRepository`, what error will occur at runtime when `myEntityService.deleteEntity(1L)` is called with this custom repository method?
java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

// Repository definition
interface MyEntityRepository extends JpaRepository<MyEntity, Long> {
    void delete(Long id); // Custom method - problematic signature
}

// Service Layer
@Service
public class MyEntityService {

    private MyEntityRepository repository; // Assume injected

    public void deleteEntity(Long id) {
        repository.delete(id);
    }
}
// Assume MyEntity class exists
Q689 medium code output
Considering the `TaskDto` and controller below, what will the `processTask` method return if the POST request body is `{"description":"Review code", "status":"COMPLETED"}`?
java
import org.springframework.web.bind.annotation.*;
import lombok.Data;

enum TaskStatus { PENDING, IN_PROGRESS, COMPLETED }

@Data
class TaskDto {
    private String description;
    private TaskStatus status;
}

@RestController
@RequestMapping("/tasks")
public class TaskController {

    @PostMapping
    public String processTask(@RequestBody TaskDto taskDto) {
        return "Task: " + taskDto.getDescription() + ", Status: " + taskDto.getStatus().name();
    }
}
Q690 medium code output
What is the HTTP status code and response body returned by this Spring Boot controller method?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
    @GetMapping("/error")
    public ResponseEntity<String> getError() {
        return ResponseEntity.badRequest().body("Validation failed.");
    }
}
Q691 medium
If a `@Controller` class needs to interact with business logic, how would it typically obtain an instance of a class annotated with `@Service`?
Q692 medium code error
What error will occur when Spring Boot attempts to create a bean for `MyService`?
java
package com.example.app;

import org.springframework.stereotype.Service;

@Service
class MyService {
    private MyService() { 
        // Private constructor
    }
    
    public String getMessage() {
        return "Hello";
    }
}
Q693 medium code error
What error will occur when accessing `/api/config?max=ten` with the following Spring Boot controller?
java
import org.springframework.web.bind.annotation.*;

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

    @GetMapping("/config")
    public String getConfig(@RequestParam(defaultValue = "5") int min,
                              @RequestParam(defaultValue = "100") int max) {
        return "Min: " + min + ", Max: " + max;
    }
}
Q694 medium code error
What error will prevent this Spring Boot application from starting?
java
package com.example.app;

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

@SpringBootApplication
public class CycleApp {
    public static void main(String[] args) {
        SpringApplication.run(CycleApp.class, args);
    }
}

@Service
class ServiceA {
    @Autowired ServiceB serviceB;
}

@Service
class ServiceB {
    @Autowired ServiceA serviceA;
}
Q695 medium code output
Consider a Spring Boot REST controller with a `@PostMapping("/register")` method that accepts a `@Valid @RequestBody UserRegistrationDto userDto`. What is the HTTP status code and response body content when the following JSON request is sent to `/register`? `POST /register HTTP/1.1 Content-Type: application/json { "username": "Carl", "email": "carl.example.com", "age": 22 }`
java
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Email;
import javax.validation.constraints.Min;

public class UserRegistrationDto {
    @NotNull(message = "Username must not be null")
    private String username;

    @NotNull(message = "Email must not be null")
    @Email(message = "Email format is invalid")
    private String email;

    @NotNull(message = "Age must not be null")
    @Min(value = 1, message = "Age must be at least 1")
    private Integer age;

    // Getters and setters are implicitly present
}
Q696 medium
For a RESTful DELETE operation targeting a specific resource by its ID (e.g., `/api/products/123`), why is `@PathVariable` generally preferred over `@RequestParam` in Spring Boot?
Q697 medium
How can you specify a default value for an optional query parameter in a Spring Boot GET request handler if the parameter is not provided in the request URL?
Q698 medium code output
A Spring Boot application with `@EnableScheduling` has the following component. What will be the approximate output (excluding stack traces) 6-7 seconds after the application starts?
java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ErrorHandlingScheduler {

    private int runCount = 0;

    @Scheduled(fixedRate = 2000)
    public void faultProneTask() {
        runCount++;
        if (runCount % 2 != 0) { // Throw error on 1st, 3rd, 5th run, etc.
            throw new RuntimeException("Task failure on run: " + runCount);
        }
        System.out.println("Fault-prone task completed successfully. Run: " + runCount);
    }
}
Q699 medium code output
What is the HTTP status code and response body for a PUT request to `/api/accounts/123` with the JSON body `{"balance": 1000.0}`?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.Map;

// Assume Account class has Long id, Double balance.

@RestController
@RequestMapping("/api/accounts")
public class AccountController {
    private Map<Long, Account> accounts = new HashMap<>();

    public AccountController() {
        accounts.put(123L, new Account(123L, 500.0));
    }

    @PutMapping("/{id}")
    public ResponseEntity<Account> updateAccount(@PathVariable Long id, @RequestBody Account accountDetails) {
        if (id == null || accountDetails == null) {
            return ResponseEntity.badRequest().build();
        }
        if (!accounts.containsKey(id)) {
            // Idempotent PUT: Create if not exists
            accountDetails.setId(id);
            accounts.put(id, accountDetails);
            return new ResponseEntity<>(accountDetails, HttpStatus.CREATED);
        }
        // Update existing
        Account existingAccount = accounts.get(id);
        existingAccount.setBalance(accountDetails.getBalance());
        accounts.put(id, existingAccount);
        return new ResponseEntity<>(existingAccount, HttpStatus.OK);
    }
}
Q700 medium
If a `@RequestParam` has both `defaultValue` and `required=false` attributes set, and the parameter is missing in the HTTP request, what value will the method argument receive?
← Prev 3334353637 Next → Page 35 of 49 · 971 questions