🌱 Spring Boot MCQ Questions

971 multiple choice questions with answers and explanations — free practice for Spring Boot interviews

▶ Practice All Spring Boot Questions
Q1 medium code output
What is the HTTP status code and response body returned by this Spring Boot controller method?
java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
    @GetMapping("/teapot")
    public ResponseEntity<String> getTeapot() {
        return ResponseEntity.status(HttpStatus.IM_A_TEAPOT).body("I am a teapot!");
    }
}
Q2 medium code output
What is the output of this code?
java
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Collections;

public class SecureService {
    @PreAuthorize("hasAuthority('ROLE_USER')")
    public String getUserProfile() { return "User Profile"; }
}

public class TestRunner {
    public static void main(String[] args) {
        SecurityContextHolder.getContext().setAuthentication(
            new UsernamePasswordAuthenticationToken("user", "pass", Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")))
        );
        SecureService service = new SecureService();
        try { System.out.println(service.getUserProfile()); }
        catch (Exception e) { System.out.println(e.getClass().getSimpleName()); }
    }
}
Q3 medium code error
When a client successfully deletes an employee using this endpoint, what HTTP status code will be returned, and why is this problematic?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

    private EmployeeService employeeService; // Assume injected

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteEmployee(@PathVariable Long id) {
        employeeService.deleteEmployee(id);
        return ResponseEntity.ok().build(); // Problematic return status
    }
}
Q4 medium code error
The following Spring Boot application attempts to use a data access class. What error will occur when the application context tries to load and `ProductService` is created?
java
package com.example.dao;

public class ProductRepositoryImpl {
    public String findProductById(Long id) {
        return "Product_" + id;
    }
}

package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.dao.ProductRepositoryImpl;

@Service
public class ProductService {
    @Autowired
    private ProductRepositoryImpl productRepository;

    public String getProductDetails(Long id) {
        return productRepository.findProductById(id);
    }
}

// Assuming a @SpringBootApplication main class exists and scans these packages.
Q5 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.stereotype.Component;

@Component
class MyService { public String message() { return "Hello ApplicationContext!"; } }

@SpringBootApplication
public class App1 {
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(App1.class, args);
        MyService service = ctx.getBean(MyService.class);
        System.out.println(service.message());
    }
}
Q6 medium code error
What error will occur when Spring tries to instantiate `MyService` given the following code?
java
import org.springframework.stereotype.Component;

@Component
public class MyService {
    private final int value;

    public MyService(int value) {
        this.value = value;
    }
}
Q7 medium code output
What does this code print to the console?
java
package com.example;

import jakarta.persistence.*;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

@Entity
public class Product {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String description;

    public Product() {}
    public Product(Long id, String name, String description) { this.id = id; this.name = name; this.description = description; }
    public String getName() { return name; }
    public String getDescription() { return description; }
}

class ProductInfoDTO {
    private String productName;
    private String productDescription;
    public ProductInfoDTO(String productName, String productDescription) {
        this.productName = productName;
        this.productDescription = productDescription;
    }
    public String getProductName() { return productName; }
    public String getProductDescription() { return productDescription; }
}

interface ProductRepository extends JpaRepository<Product, Long> {
    @Query("SELECT NEW com.example.ProductInfoDTO(p.name, p.description) FROM Product p WHERE p.id = :id")
    ProductInfoDTO findProductInfoByIdJPQL(@Param("id") Long id);
}

// Assume ProductRepository is autowired as 'productRepository'
// And the database contains: Product(id=1, name='Router', description='Wireless AC Router')
ProductInfoDTO dto = productRepository.findProductInfoByIdJPQL(1L);
System.out.println(dto.getProductName());
Q8 medium code output
A Spring Boot application with `@EnableScheduling` uses the following configuration and component. What is the output related to the scheduled task after 10-12 seconds of runtime? `application.properties`: `app.task.rate=3000`
java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;

@Component
public class PropertyBasedScheduler {

    @Value("${app.task.rate}")
    private long configuredRate;

    private int counter = 0;

    @Scheduled(fixedRateString = "${app.task.rate}")
    public void runPropertyBasedTask() {
        System.out.println("Property Based Task executed. Configured Rate: " + configuredRate + ". Counter: " + counter++);
    }
}
Q9 medium code output
Given `application.properties` does NOT contain `app.version` 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 VersionService {
    @Value("${app.version:1.0.0}")
    private String appVersion;

    public String getVersion() {
        return appVersion;
    }
}
// In a Spring Boot application, if this component is scanned:
// VersionService service = applicationContext.getBean(VersionService.class);
// System.out.println(service.getVersion());
Q10 medium code output
What does this code print?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service static class MyDataService { public String getData() { return "Data from Service"; } }

@Component
@SpringBootApplication
public class MyApplication {
    private final MyDataService dataService;
    @Autowired public MyApplication(MyDataService dataService) { this.dataService = dataService; }
    public String process() { return "Processing: " + dataService.getData(); }
    public static void main(String[] args) {
        MyApplication app = SpringApplication.run(MyApplication.class, args).getBean(MyApplication.class);
        System.out.println(app.process());
    }
}
Q11 medium code output
What does this code print?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@SpringBootApplication
public class MyApplication {
    @Bean @ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
    public String myConditionalBean() { return "Conditional Bean Created"; }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.setDefaultProperties(java.util.Collections.singletonMap("feature.enabled", "true"));
        ConfigurableApplicationContext ctx = app.run(args);
        try { System.out.println(ctx.getBean("myConditionalBean", String.class)); }
        catch (org.springframework.beans.factory.NoSuchBeanDefinitionException e) { System.out.println("Conditional Bean NOT Created"); }
    }
}
Q12 medium
What is the consequence if you declare an `@RequestParam(required = false)` for a primitive type (e.g., `int`) and the parameter is missing in the request?
Q13 medium
How can you enable automatic validation for an object bound with `@RequestBody` in a Spring Boot controller method?
Q14 medium
Which of the following annotations is used within a `@RestController` method to bind the incoming HTTP request body to a method parameter?
Q15 medium code error
What error prevents this Spring Boot application from starting successfully?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {

    @Autowired
    private static String appName; // Static fields cannot be autowired

    public void displayAppName() {
        System.out.println("Application Name: " + appName);
    }
}
Q16 medium code output
What is the output of this code when `App` is executed?
java
import javax.annotation.PostConstruct;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Component;

@Component
class MyBean {
    public MyBean() { System.out.println("1. MyBean Constructor"); }
    @PostConstruct public void init() { System.out.println("2. MyBean @PostConstruct"); }
}
@ComponentScan
public class App {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);
        context.close();
    }
}
Q17 medium code error
What is the expected error when a client sends a GET request to /api/items without a Content-Type header?
java
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

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

    @GetMapping(value = "/items", consumes = MediaType.APPLICATION_JSON_VALUE)
    public String getItems() {
        return "Items list";
    }
}
Q18 medium code output
What will be the exact path (including the query parameter) that the browser is redirected to after the `saveData` method is called with a POST request?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class RedirectController {
    @PostMapping("/data/save")
    public String saveData(RedirectAttributes redirectAttributes) {
        redirectAttributes.addAttribute("status", "success");
        redirectAttributes.addFlashAttribute("message", "Data saved successfully!");
        return "redirect:/status";
    }
}
Q19 medium code output
What is the output of this code snippet, assuming there are 2 `Product` entities with `category="Electronics"` and the `deleteByCategory` method is called within a Spring-managed transaction?
java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;

interface ProductRepository extends JpaRepository<Product, Long> {
    @Transactional
    Long deleteByCategory(String category);
}

// Assuming Product and ProductRepository are properly defined and wired
// and 'productRepository' is an injected instance.
// Simulate DB content: Product(id=1, name='TV', category='Electronics')
//                     Product(id=2, name='Phone', category='Electronics')
//                     Product(id=3, name='Book', category='Books')

public class TestService {
    ProductRepository productRepository;

    public TestService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    public Long performDelete() {
        return productRepository.deleteByCategory("Electronics");
    }
}
// In a conceptual main method or test:
// System.out.println(new TestService(productRepositoryMock).performDelete());
Q20 medium
Which annotation is primarily used in Spring Boot to automatically inject dependencies into a class field, constructor, or setter method, embodying IoC?
123 Next → Page 1 of 49 · 971 questions