🌱 Spring Boot MCQ Questions – Page 6

Questions 101–120 of 971 total — Spring Boot interview practice

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

// Assume Widget class has Long id, String name, String category (nullable).

@RestController
@RequestMapping("/api/widgets")
public class WidgetController {
    private Map<Long, Widget> widgets = new HashMap<>();

    public WidgetController() {
        widgets.put(1L, new Widget(1L, "Old Widget", "Electronics"));
    }

    @PutMapping("/{id}")
    public ResponseEntity<Widget> updateWidget(@PathVariable Long id, @RequestBody Widget widgetDetails) {
        if (!widgets.containsKey(id)) {
            return ResponseEntity.status(404).build();
        }
        Widget existingWidget = widgets.get(id);
        // Only update provided fields. PUT is generally full replacement, but this code shows partial update logic.
        if (widgetDetails.getName() != null) {
            existingWidget.setName(widgetDetails.getName());
        }
        // Category is not in request body, so it remains unchanged by this logic.
        widgets.put(id, existingWidget);
        return ResponseEntity.status(200).body(existingWidget);
    }
}
Q102 medium
Which attribute of `@RequestParam` is used to provide a fallback value for the parameter if it is not present in the HTTP request?
Q103 medium
To handle a GET request where a path segment (e.g., an 'id') is optional (e.g., `/items` versus `/items/{id}`), what is the most common and robust approach in Spring Boot?
Q104 medium code output
What is the output of this code when `App` is executed?
java
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Component;

@Component
class MyNamedBean implements BeanNameAware {
    private String name;
    public MyNamedBean() { System.out.println("1. Ctor"); }
    @Override
    public void setBeanName(String name) { this.name = name; System.out.println("2. setBeanName: " + name); }
    public String getBeanName() { return name; }
}
@ComponentScan
public class App {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);
        MyNamedBean bean = context.getBean(MyNamedBean.class);
        System.out.println("3. Retrieved: " + bean.getBeanName());
        context.close();
    }
}
Q105 medium code error
What is the consequence of adding `@ComponentScan(basePackages = "com.example.other")` to the `@SpringBootApplication` class in `com.example.app` while expecting components in `com.example.app.service` to be scanned?
java
package com.example.app;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;

package com.example.app.service;

@Service
public class MyService {
    // Service implementation
}

// In com.example.app package
@SpringBootApplication
@ComponentScan(basePackages = "com.example.other")
public class ScanApp {
    public static void main(String[] args) {
        SpringApplication.run(ScanApp.class, args);
    }
}
Q106 medium
When Spring encounters multiple beans of the same type during autowiring, and there's no primary bean or qualifier specified, what exception is typically thrown?
Q107 medium code output
Assume there is a `@RestController` with a `/hello` endpoint that returns "Hello from Controller!". What does this code print to the console when `testHelloEndpoint` is executed?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.web.servlet.MockMvc;
import org.junit.jupiter.api.Test;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class MockMvcTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void testHelloEndpoint() throws Exception {
        String response = mockMvc.perform(get("/hello"))
                                 .andExpect(status().isOk())
                                 .andReturn().getResponse().getContentAsString();
        System.out.println(response);
    }
}
Q108 medium
Which of the following `@RequestMapping` attributes specifies the media types that the controller method can consume (i.e., accept from the request body)?
Q109 medium
Which Spring Boot annotation is primarily used to map HTTP DELETE requests to a specific handler method in a REST controller?
Q110 medium code output
An unauthenticated client attempts to access the `/css/style.css` endpoint. What is the expected HTTP status code and response body?
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/css/**", "/js/**", "/images/**").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin(withDefaults())
            .csrf(csrf -> csrf.disable());
        return http.build();
    }
}

@RestController
public class ResourceController {
    @GetMapping("/css/style.css")
    public String getCss() { return "/* CSS content */"; }

    @GetMapping("/app/data")
    public String getAppData() { return "Application data"; }
}
Q111 medium code error
What error will occur when accessing `/api/data?id=abc` with the following Spring Boot controller?
java
import org.springframework.web.bind.annotation.*;
import java.util.Optional;

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

    @GetMapping("/data")
    public String getData(@RequestParam Optional<Integer> id) {
        return "ID: " + id.orElse(0);
    }
}
Q112 medium
When implementing a service method that orchestrates multiple repository operations, what is a common best practice regarding data consistency and failure handling?
Q113 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.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.annotation.Bean;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
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");
            }
        };
    }
}
Q114 medium code error
What happens if a client attempts to access `/items/{id}` with `{id}` being a non-numeric string (e.g., `/items/abc`) using this controller?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ItemController {

    @GetMapping("/items/{id}")
    @ResponseBody
    public String getItem(@PathVariable("id") Long itemId) {
        return "Item ID: " + itemId;
    }
}
Q115 medium code output
Assuming a Spring Boot application with the following controller, what is the outcome regarding the view and model attributes if a request is made to `/data`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class DataController {

    @GetMapping("/data")
    public ModelAndView getData() {
        ModelAndView mav = new ModelAndView("showData");
        mav.addObject("item", "Laptop");
        mav.addObject("price", 1200.00);
        return mav;
    }
}
Q116 medium code error
What will happen when this application attempts to start if `spring.main.web-application-type=NONE` is configured in `application.properties`?
java
package com.example.app;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.web.bind.annotation.RestController;

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

    // ... endpoint definitions
}
Q117 medium code error
What error will occur when Spring attempts to autowire `MyProcessor` into `ServiceUser`?
java
import org.springframework.stereotype.Component;

interface MyProcessor {
    void process();
}

@Component
class DefaultProcessor implements MyProcessor {
    @Override public void process() {}
}

@Component
class SpecialProcessor implements MyProcessor {
    @Override public void process() {}
}

@Component
class ServiceUser {
    private final MyProcessor processor;
    public ServiceUser(MyProcessor processor) {
        this.processor = processor;
    }
}
Q118 medium
To enable Cross-Origin Resource Sharing (CORS) for a specific controller method, allowing requests from `http://example.com`, which annotation would be applied to the method?
Q119 medium code error
Given the following Spring Boot configuration with `proxyBeanMethods = false`, what will be the runtime error when `MyService` attempts to use `dependencyService`?
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Autowired;

public class DependencyService {
    public String getData() { return "Data"; }
}

public class MyService {
    @Autowired
    private DependencyService dependencyService;
    public String getInfo() {
        if (dependencyService == null) throw new IllegalStateException("DependencyService not injected!");
        return "MyService info: " + dependencyService.getData();
    }
}

@Configuration(proxyBeanMethods = false)
public class AppConfig {
    @Bean
    public DependencyService dependencyService() { return new DependencyService(); }

    @Bean
    public MyService myService() {
        // Direct call, bypassing Spring's full bean lifecycle management
        return new MyService(); 
    }

    // Assume the main application calls: 
    // context.getBean(MyService.class).getInfo();
}
Q120 medium code error
What is the error encountered when a client sends a POST request to `/items` with an empty request body, given the following Spring Boot controller method?
java
package com.example.demo;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

@RestController
public class ItemController {
    @PostMapping("/items")
    public ResponseEntity<String> createItem(@RequestBody Item item) {
        return ResponseEntity.ok("Item created: " + item.getName());
    }
}
// Item class has a default constructor and setters.
← Prev 45678 Next → Page 6 of 49 · 971 questions