🌱 Spring Boot MCQ Questions – Page 4

Questions 61–80 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q61 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": "Bob", "email": "bob@example.com", "age": 0 }`
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
}
Q62 medium code error
What error will occur when accessing `/api/scores?values=10,abc,20` with the following Spring Boot controller?
java
import org.springframework.web.bind.annotation.*;
import java.util.Set;

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

    @GetMapping("/scores")
    public String getScores(@RequestParam Set<Integer> values) {
        return "Total values: " + values.size();
    }
}
Q63 medium code output
What is the output printed to the console when the following Spring Boot `@Service` definitions using constructor injection and their usage are executed? (Assume standard Spring Boot application setup and necessary imports.)
java
import org.springframework.stereotype.Service;

@Service
class DependencyService { public String getMessage() { return "Dependent Data"; } }

@Service
class MainService {
    private final DependencyService depService;
    public MainService(DependencyService depService) { this.depService = depService; }
    public String getFullMessage() { return "Main: " + depService.getMessage(); }
}

// In a @SpringBootApplication's CommandLineRunner, after autowiring:
// System.out.println(mainService.getFullMessage());
Q64 medium code output
Assume `ExternalService` is an interface with `fetchData()` returning "Real Data" in its `ExternalServiceImpl` implementation, and `MyProcessor` uses `ExternalService`. What does this code print to the console when `testMockedService` is executed?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.when;

// ExternalService, ExternalServiceImpl, and MyProcessor (not shown)
@SpringBootTest
public class MockBeanTest {

    @MockBean
    private ExternalService externalService;

    @Autowired
    private MyProcessor myProcessor;

    @Test
    void testMockedService() {
        when(externalService.fetchData()).thenReturn("Mocked Data");
        System.out.println(myProcessor.processData()); // MyProcessor.processData() calls externalService.fetchData()
    }
}
Q65 medium code error
What will be the outcome when running this Spring Boot application, specifically when `greeter.performGreeting()` is called?
java
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Component;

public interface GreetingService {
    String greet();
}

@Service("formalGreeting")
public class FormalGreetingService implements GreetingService {
    @Override public String greet() { return "Good day!"; }
}

@Service("informalGreeting")
public class InformalGreetingService implements GreetingService {
    @Override public String greet() { return "Hey there!"; }
}

@Component
public class Greeter {
    // @Autowired is missing
    @Qualifier("formalGreeting")
    private GreetingService greetingService;

    public void performGreeting() {
        System.out.println(greetingService.greet());
    }
}
Q66 medium code error
What error will you encounter when compiling this Java code snippet in a Spring Boot context?
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("/invalid-header")
    public ResponseEntity<String> getInvalidHeader() {
        return ResponseEntity.ok().header("X-Custom-Value", 123).build();
    }
}
Q67 medium code error
What happens when a client sends a JSON payload `{"amount": 99.99}` to this POST endpoint expecting to populate `InvoiceDto`?
java
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/invoices")
public class InvoiceController {
    @PostMapping
    public String createInvoice(@ModelAttribute InvoiceDto invoice) {
        return "Invoice created for " + invoice.getAmount();
    }
}

class InvoiceDto {
    private double amount;
    public double getAmount() { return amount; }
    public void setAmount(double amount) { this.amount = amount; }
}
Q68 medium code output
What will be printed to the console when this Spring Boot application attempts to start?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
class ServiceX {
    private ServiceY serviceY;

    @Autowired
    public void setServiceY(ServiceY serviceY) {
        this.serviceY = serviceY;
    }

    public String getX() { return "X"; }
}

@Component
class ServiceY {
    private ServiceX serviceX;

    @Autowired
    public ServiceY(ServiceX serviceX) {
        this.serviceX = serviceX;
    }

    public String getY() { return "Y"; }
}

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        try {
            SpringApplication.run(MyApplication.class, args);
        } catch (Exception e) {
            if (e.getCause() instanceof org.springframework.beans.factory.BeanCurrentlyInCreationException) {
                System.out.println("Circular dependency detected.");
            } else if (e.getCause() instanceof org.springframework.beans.factory.UnsatisfiedDependencyException) {
                System.out.println("Unsatisfied dependency.");
            } else {
                System.out.println("Application startup failed due to: " + e.getMessage());
            }
        }
    }
}
Q69 medium code output
What is the approximate output after 10-12 seconds of the application running, given the following scheduled task, assuming the application starts at T=0?
java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class CombinedScheduler {

    private int counter = 0;

    @Scheduled(initialDelay = 1000, fixedDelay = 3000) 
    public void runCombinedTask() throws InterruptedException {
        System.out.println("Combined Task executed. Counter: " + counter++);
        Thread.sleep(1000); // Simulate work
    }
}
Q70 medium code error
What is the result when this Spring Boot application starts?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

class ConfigData {
    private String value = "default";
    public String getValue() { return value; }
}

@Component
class MyProcessor {
    private ConfigData config;

    @Autowired
    public void initialize(ConfigData config) {
        this.config = config;
    }

    public String getConfigValue() { return config.getValue(); }
}
Q71 medium code error
What is the outcome when this Spring Boot application attempts to create the `userService` bean?
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean(initMethod = "setupUsers") // Method 'setupUsers' does not exist
    public UserService userService() {
        return new UserService();
    }
}

class UserService {
    public void init() {
        System.out.println("UserService initialized.");
    }
}
Q72 medium code output
What is the HTTP status code and response body for a PUT request to `/api/books/1` with the JSON body `{"title": "Effective Java", "author": "Joshua Bloch", "isbn": null}`?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.Map;

// Assume Book class has Long id, String title, String author, String isbn, with getters/setters/constructor.

@RestController
@RequestMapping("/api/books")
public class BookController {
    private Map<Long, Book> books = new HashMap<>();

    public BookController() {
        books.put(1L, new Book(1L, "Clean Code", "Robert C. Martin", "978-0132350884"));
    }

    @PutMapping("/{id}")
    public ResponseEntity<Book> replaceBook(@PathVariable Long id, @RequestBody Book bookDetails) {
        if (!books.containsKey(id)) {
            // For PUT, if resource does not exist, it's often created. Let's make it strict here.
            return ResponseEntity.notFound().build();
        }
        bookDetails.setId(id); // Ensure the ID from path variable is used
        books.put(id, bookDetails);
        return ResponseEntity.ok(bookDetails);
    }
}
Q73 medium code output
What URI will be used for a request to `/my-service/data` if the gateway is running with a discovery client (e.g., Eureka)?
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("load_balanced_route", r -> r.path("/my-service/**")
                        .uri("lb://MY-SERVICE"))
                .build();
    }
}
Q74 medium code output
Assuming H2 database is on the classpath, what is the output of this code when the `main` method of `MyApplication` is executed?
java
// src/main/java/com/example/demo/MyApplication.java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.annotation.Bean;

@SpringBootApplication(excludeName = {"org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration"})
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

    @Bean
    public CommandLineRunner checkDataSourceBean(ApplicationContext context) {
        return args -> {
            try {
                context.getBean(javax.sql.DataSource.class);
                System.out.println("DataSource bean found");
            } catch (NoSuchBeanDefinitionException e) {
                System.out.println("DataSource bean not found");
            }
        };
    }
}
Q75 medium code output
What is the output of this Spring Boot application?
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 MessageService { String sendMessage(); }

@Component("smsService")
class SmsService implements MessageService { @Override public String sendMessage() { return "Sending SMS message"; } }

@Component("emailService")
class EmailService implements MessageService { @Override public String sendMessage() { return "Sending email message"; } }

@Component
class MyRunner implements CommandLineRunner {
    @Autowired
    @Qualifier("smsService")
    private MessageService messageService;

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

@SpringBootApplication
class MyApp {}
Q76 medium code error
A Spring Boot application defines a Spring Data JPA repository interface extending `JpaRepository`. If the main configuration class is missing the `@EnableJpaRepositories` annotation, what error will occur during application startup?
java
package com.example.domain;
import jakarta.persistence.Entity; import jakarta.persistence.Id; @Entity public class Product { @Id private Long id; private String name; }

package com.example.repository;
import org.springframework.data.jpa.repository.JpaRepository;

public interface MyProductRepository extends JpaRepository<Product, Long> {
}

package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.repository.MyProductRepository;

@Service
public class ProductManagementService {
    @Autowired
    private MyProductRepository productRepository;
    public Product getProduct(Long id) { return productRepository.findById(id).orElse(null); }
}
// Assuming @SpringBootApplication main class but NO @EnableJpaRepositories.
Q77 medium code output
What is the output of this code snippet, assuming `userRepository` initially contains users with IDs 1, 2, and 3?
java
import java.util.List;
import java.util.stream.Collectors;

public class UserService {
    private UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public List<String> getAllUserNames() {
        return userRepository.findAll()
                             .stream()
                             .map(User::getName)
                             .collect(Collectors.toList());
    }
}

// In a test context or main method (assuming users are 'Alice', 'Bob', 'Charlie'):
UserService service = new UserService(userRepository);
List<String> names = service.getAllUserNames();
System.out.println(names.size() > 0 ? String.join(", ", names) : "No users found");
Q78 medium
Which of the following HTTP headers is most crucial for `@RequestBody` to correctly deserialize an incoming JSON request body into a Java object?
Q79 medium code output
What will be printed to the console when this Spring Boot application starts?
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 DataService { String getData(); }

@Component("cloudDataService")
class CloudDataService implements DataService { @Override public String getData() { return "Data from Cloud"; } }

@Component("localDataService")
class LocalDataService implements DataService { @Override public String getData() { return "Data from Local Storage"; } }

@Component
class DataProcessor {
    private final DataService dataService;

    @Autowired
    public DataProcessor(@Qualifier("localDataService") DataService dataService) {
        this.dataService = dataService;
    }

    public String processAndGetData() { return "Processing " + dataService.getData(); }
}

@Component
class ProcessorRunner implements CommandLineRunner {
    @Autowired
    private DataProcessor processor;

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

@SpringBootApplication
class App {}
Q80 medium
What happens if a required `@RequestBody` is missing from an incoming HTTP request in a Spring Boot application?
← Prev 23456 Next → Page 4 of 49 · 971 questions