🌱 Spring Boot MCQ Questions – Page 14

Questions 261–280 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q261 medium code output
What is the HTTP status code and 'X-Custom-Header' value returned by this Spring Boot controller method?
java
import org.springframework.http.HttpHeaders;
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("/headers")
    public ResponseEntity<String> getWithHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Custom-Header", "MyValue");
        return new ResponseEntity<>("Data", headers, HttpStatus.OK);
    }
}
Q262 medium code error
If the `run` method of `AppRunner` is executed, what will be the outcome?
java
import org.springframework.stereotype.Repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Repository class MyRepo { public String getData() { return "Data"; } }

// NOT a Spring managed class
class NonSpringManagedClass {
    @Autowired private MyRepo myRepo; 
    public String performAction() { return myRepo.getData(); }
}

@Component class AppRunner implements CommandLineRunner {
    @Override public void run(String... args) throws Exception {
        new NonSpringManagedClass().performAction(); 
    }
}
Q263 medium code error
What error will occur when this Spring Boot application starts if `spring-boot-starter-data-jpa` is missing from the classpath?
java
package com.example.app;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

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

@Repository
interface MyEntityRepository extends JpaRepository<Object, Long> {}
Q264 medium code error
Consider the following Spring Boot code. What error will it produce upon compilation?
java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

public class ResponseEntityTest {
    public ResponseEntity<String> getNumericalData() {
        Integer number = 42;
        return ResponseEntity.ok(number);
    }
}
Q265 medium
What is a key difference in usage between `@PathVariable` and `@RequestParam`?
Q266 medium code output
Given this Spring Boot controller method, what HTTP status code and body will the client receive if a DELETE request targets `/api/orders/789` and the order is successfully removed?
java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    private OrderService orderService;

    // Constructor injected orderService

    @DeleteMapping("/{id}")
    public ResponseEntity<String> cancelOrder(@PathVariable Long id) {
        orderService.cancelOrder(id);
        return new ResponseEntity<>("Order cancelled successfully.", HttpStatus.OK);
    }
}
Q267 medium code output
What is the HTTP response body when a GET request is made to `/search/java%20spring`?
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 SearchController {
    @GetMapping("/search/{query}")
    public String performSearch(@PathVariable String query) {
        return "Searching for: " + query;
    }
}
Q268 medium
What is the primary use of the `@ModelAttribute` annotation on a method parameter in a Spring MVC controller for view rendering?
Q269 medium code error
What error will occur when this Spring Boot application attempts to start?
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 MyController {

    @GetMapping("/items/{id:[a-z}")
    public String getItemById(@PathVariable String id) {
        return "Item ID: " + id;
    }
}
Q270 medium
Which of the following statements best describes the primary additional capability that Spring's `ApplicationContext` provides compared to a basic `BeanFactory`?
Q271 medium code output
What is the output of this code when `App` is executed?
java
import javax.annotation.PostConstruct;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Component;

@Component class MyBean { public MyBean() { System.out.println("1. MyBean Ctor"); } @PostConstruct public void init() { System.out.println("3. MyBean @PostConstruct"); } }
@Component class MyProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object b, String n) throws BeansException { if (b instanceof MyBean) System.out.println("2. Before Init: " + n); return b; } @Override public Object postProcessAfterInitialization(Object b, String n) throws BeansException { return b; } }
@ComponentScan
public class App { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class); context.close(); } }
Q272 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.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@SpringBootApplication
public class MyApplication {
    static class DataSource {
        private static int instanceCount = 0;
        public DataSource() { instanceCount++; }
        public String getConnectionUrl() { return "jdbc:mysql://localhost/db" + instanceCount; }
    }
    static class MyRepository {
        private final DataSource dataSource;
        public MyRepository(DataSource ds) { this.dataSource = ds; }
        public String getRepositoryInfo() { return "Repo using " + dataSource.getConnectionUrl(); }
    }
    @Bean public DataSource dataSource() { System.out.println("Creating new DataSource instance"); return new DataSource(); }
    @Bean public MyRepository myRepository() { return new MyRepository(dataSource()); } // Spring intercepts
    public static void main(String[] args) {
        MyRepository repository = SpringApplication.run(MyApplication.class, args).getBean(MyRepository.class);
        System.out.println(repository.getRepositoryInfo());
    }
}
Q273 medium code output
Given `application.properties` contains `server.port=8080` 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 PortChecker {
    @Value("#{${server.port} > 8000 ? 'High Port' : 'Low Port'}")
    private String portStatus;

    public String getPortStatus() {
        return portStatus;
    }
}
// In a Spring Boot application, if this component is scanned:
// PortChecker checker = applicationContext.getBean(PortChecker.class);
// System.out.println(checker.getPortStatus());
Q274 medium
Which annotation is commonly used in conjunction with `@Service` methods to define transactional boundaries for business operations?
Q275 medium
What is the primary benefit of using `ResponseEntity` in a Spring Boot REST controller instead of simply returning a POJO or String?
Q276 medium code error
What error will occur when the Spring application context attempts to initialize these components?
java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@Component
public class ComponentA {
    private final ComponentB b;
    public ComponentA(ComponentB b) {
        this.b = b;
    }
}

@Component
public class ComponentB {
    private final ComponentA a;
    public ComponentB(ComponentA a) {
        this.a = a;
    }
}
Q277 medium code output
What is the expected outcome (exception) if a POST request with body `{"name":""}` is sent to the following controller, considering the validation annotations?
java
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;

@Data
class NameDto {
    @NotBlank(message = "Name cannot be blank")
    private String name;
}

@RestController
@RequestMapping("/names")
public class NameController {

    @PostMapping
    public String submitName(@Valid @RequestBody NameDto nameDto) {
        return "Name submitted: " + nameDto.getName();
    }
}
Q278 medium code error
What error occurs when accessing `/api/data/123` with the following controller?
java
import org.springframework.web.bind.annotation.*;

@RestController
public class DataController {
    @GetMapping("/api/data/{id}")
    public String getData(@RequestParam String id) {
        return "Data ID: " + id;
    }
}
Q279 medium code output
What is the output when '/admin/users' is accessed, considering both local and global handlers?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;

// Assumed: GlobalExceptionHandler.java with @ControllerAdvice exists:
// @ControllerAdvice
// public class GlobalExceptionHandler {
//    @ExceptionHandler(IllegalStateException.class)
//    public ResponseEntity<String> handleGlobalState(IllegalStateException ex) {
//        return new ResponseEntity<>("Global State Error: " + ex.getMessage(), HttpStatus.CONFLICT);
//    }
// }

@RestController
@RequestMapping("/admin")
public class AdminController {
    @GetMapping("/users")
    public String getUsers() {
        throw new IllegalStateException("User session invalid");
    }

    @ExceptionHandler(IllegalStateException.class)
    public ResponseEntity<String> handleLocalState(IllegalStateException ex) {
        return new ResponseEntity<>("Local State Problem: " + ex.getMessage(), HttpStatus.UNAUTHORIZED);
    }
}
Q280 medium code error
What will be the outcome during the Spring Boot application startup?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
class ServiceA {}

@Component
class ServiceB {}

@Component
class MyConsumer {
    @Autowired
    public MyConsumer(ServiceA serviceA) {}

    @Autowired
    public MyConsumer(ServiceB serviceB) {}
}
← Prev 1213141516 Next → Page 14 of 49 · 971 questions