🌱 Spring Boot MCQ Questions – Page 19

Questions 361–380 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q361 medium code output
Assuming a global configuration defines a `String` bean `appMessage` returning "Original Message", what is the output of this test code?
java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;

@SpringBootTest
class TestConfigurationOverrideTest {
    @Autowired
    String appMessage;

    @Test
    void testMessageOverride() {
        System.out.print(appMessage);
    }

    @TestConfiguration
    static class MyTestConfig {
        @Bean
        public String appMessage() {
            return "Test Overridden Message";
        }
    }
}
Q362 medium code output
What is the output of this code when a GET request is made to '/items'?
java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ItemController {
    @GetMapping("/items")
    public String getItems() {
        return "List of items.";
    }

    @PostMapping("/items")
    public String createItem() {
        return "Item created.";
    }
}
Q363 medium code output
What is the output when accessing `/params?id=123&name=TestUser&status=active`?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.Map;

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

    @GetMapping("/params")
    public String getAllParams(@RequestParam Map<String, String> allParams) {
        return "Received parameters: " + allParams;
    }
}
Q364 medium
Which of the following annotations is primarily used within a `@Configuration` class to explicitly declare a single bean definition, allowing for complex setup logic or when defining beans for third-party classes?
Q365 medium
You have two distinct beans of the same type in your Spring `ApplicationContext`. Which annotation would you use with `@Autowired` to specify which particular bean should be injected by its name or qualifier?
Q366 medium code output
What is typically printed to the console when this Spring Boot application starts up with `spring-boot-starter-security` on the classpath, without any custom security configuration?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class HomeController {
    @GetMapping("/")
    public String home() {
        return "Welcome!";
    }
}
Q367 medium code error
What error will prevent this code from compiling?
java
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping(value = "/api/data", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public String getData() {
        return "{ \"key\": \"value\" }";
    }
}
Q368 medium
Which of the following annotations acts as a general-purpose stereotype for any Spring-managed component, and is also the meta-annotation for more specific types like `@Service` and `@Repository`?
Q369 medium code output
What is the approximate output after 5-6 seconds of the application running, given the following scheduled task? Assume the application starts at T=0.
java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class InitialDelayScheduler {

    private int counter = 0;

    @Scheduled(initialDelay = 2000, fixedRate = 1000)
    public void runInitialDelayTask() {
        System.out.println("Initial Delay Task executed. Counter: " + counter++);
    }
}
Q370 medium code output
In the following controller, what HTTP status code and body would be returned if a DELETE request is sent to `/api/accounts/123` and `accountService.archiveAccount(123L)` throws a `PermissionDeniedException` (a custom unchecked exception without `@ResponseStatus`)?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;

// Assume PermissionDeniedException extends RuntimeException

@RestController
@RequestMapping("/api/accounts")
public class AccountController {

    private AccountService accountService;

    // Constructor injected accountService

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> archiveAccount(@PathVariable Long id) {
        accountService.archiveAccount(id);
        return ResponseEntity.noContent().build();
    }
}
Q371 medium code error
What error will occur at runtime if a POST request with `Content-Type: text/plain` is sent with a JSON body `{"name": "Bob"}` to the `/api/create` endpoint?
java
import org.springframework.web.bind.annotation.*;

@RestController
public class MyController {
    @PostMapping("/api/create")
    public String create(@RequestBody MyDto dto) {
        return "Created: " + dto.getName();
    }
}
// Assume MyDto exists with public String getName();
Q372 medium
To conditionally register a bean only if a specific configuration property exists and has a particular value, which annotation would you use?
Q373 medium code output
Given the following Feign client interface and a simulated call, what is the output of this code?
java
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(name = "userService", url = "http://localhost:8080")
interface UserServiceClient {
    @GetMapping("/users/{id}")
    String getUserDetails(@PathVariable("id") Long id);
}

public class TestApplication {
    public static void main(String[] args) {
        UserServiceClient client = id -> "User ID: " + id + " | Name: John Doe"; // Mock implementation
        System.out.println(client.getUserDetails(123L));
    }
}
Q374 medium
Which of the following options correctly describes how to allow overriding bean definitions in a Spring Boot application if the same bean ID is defined multiple times?
Q375 medium code output
What is the expected outcome when saving a `Report` associated with an existing `User`, where `Report` uses `@MapsId` to share the primary key with `User`?
java
import jakarta.persistence.*;

@Entity
public class User {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
    private String username;
    public User() {} public User(String username) { this.username = username; } public Long getId() { return id; }
}

@Entity
public class Report {
    @Id private Long userId;
    @MapsId("userId")
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User user;
    private String reportContent;
    public Report() {} public Report(User user, String content) { this.user = user; this.reportContent = content; }
    public Long getUserId() { return userId; } public User getUser() { return user; }
}

// Assume userRepository and reportRepository are injected
// Assume transaction context is active
User newUser = new User("testuser");
userRepository.save(newUser);

Report report = new Report(newUser, "Monthly activity report");
reportRepository.save(report);

System.out.println("User ID: " + newUser.getId() + ", Report User ID: " + report.getUserId());
Q376 medium code output
What is the HTTP status and body returned by the `submitReport` method when a POST request is made to `/reports?type=bug` with the JSON body `{"details": "App crash"}` (Content-Type: application/json)?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

class Report {
    private String details;
    public String getDetails() { return details; }
    public void setDetails(String details) { this.details = details; }
}

@RestController
@RequestMapping("/reports")
class ReportController {
    @PostMapping
    public ResponseEntity<String> submitReport(@RequestParam(required = false) String type, @RequestBody Report report) {
        String response = "Report details: " + report.getDetails();
        if (type != null && !type.isEmpty()) {
            response += " (Type: " + type + ")";
        }
        return new ResponseEntity<>(response, HttpStatus.ACCEPTED);
    }
}
Q377 medium code error
What will be the outcome when starting a Spring Boot application with this configuration?
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

// Assume 'com.example.NonSpringDependency' is a simple POJO, not a Spring bean.
package com.example;
public class NonSpringDependency {}

@Configuration
public class AppConfig {
    @Bean
    public String myService(NonSpringDependency dependency) {
        return "Service using " + dependency.getClass().getSimpleName();
    }
Q378 medium code output
What is the output of the following Spring Boot code?
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;

interface PaymentGateway { String processPayment(); }

@Component("paypalGateway")
class PayPalGateway implements PaymentGateway { @Override public String processPayment() { return "Processing payment via PayPal"; } }

@Component("stripeGateway")
class StripeGateway implements PaymentGateway { @Override public String processPayment() { return "Processing payment via Stripe"; } }

@Component
class PaymentRunner implements CommandLineRunner {
    @Autowired
    @Qualifier("paypalGateway")
    private PaymentGateway selectedGateway;

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

@SpringBootApplication
class App {}
Q379 medium
A controller method needs to accept an optional query parameter named `page`. If the parameter is not present, it should default to `1`. How would you correctly define this parameter in the method signature?
Q380 medium code output
Given the Spring Boot controller above, what will be the HTTP response body when a GET request is made to `/data/products/500`?
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 DataController {
    @GetMapping("/data/{category}/{id}")
    public String getResource(@PathVariable String category, @PathVariable int id) {
        return "Category: " + category + ", ID: " + id;
    }
}
← Prev 1718192021 Next → Page 19 of 49 · 971 questions