🌱 Spring Boot MCQ Questions – Page 21

Questions 401–420 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q401 medium
Which of the following represents the correct sequence of major phases for a singleton bean's lifecycle managed by the Spring container?
Q402 medium code output
Given the Spring Boot code, what will be the HTTP status code and response body when a GET request is made to `/resource/missing`?
java
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) { super(message); }
}

@RestController
class ResourceController {
    @GetMapping("/resource/missing")
    public String getMissingResource() {
        throw new ResourceNotFoundException("The requested resource was not found");
    }
}

@RestControllerAdvice
class SimpleErrorHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleResourceNotFound(ResourceNotFoundException ex) {
        return ex.getMessage();
    }
}
Q403 medium code output
Given the Spring Boot code below, what will be printed to the console?
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 PaymentGateway {
    public String processPayment() {
        return "Payment processed.";
    }
}

@Component
class OrderService {
    private PaymentGateway gateway;

    @Autowired
    public void setPaymentGateway(PaymentGateway gateway) {
        this.gateway = gateway;
    }

    public void placeOrder() {
        System.out.println("Order placed. " + gateway.processPayment());
    }
}

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        var context = SpringApplication.run(MyApplication.class, args);
        OrderService orderService = context.getBean(OrderService.class);
        orderService.placeOrder();
    }
}
Q404 medium code output
What is the HTTP status and JSON body returned by the `postStatus` method when a POST request is made to `/status` with the body `"Hello"` (Content-Type: text/plain)?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;

class StatusMessage {
    private String message;
    public StatusMessage(String message) { this.message = message; }
    public String getMessage() { return message; }
    public void setMessage(String message) { this.message = message; }
}

@RestController
@RequestMapping("/status")
class StatusController {
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public StatusMessage postStatus(@RequestBody String input) {
        return new StatusMessage("Received: " + input);
    }
}
Q405 medium code output
Consider a Eureka client application configured as follows. How will this instance appear in the Eureka dashboard with respect to its zone information?
yaml
spring:
  application:
    name: pricing-service

server:
  port: 8085

eureka:
  instance:
    metadataMap:
      zone: us-east-1
    hostname: pricing-service-01
Q406 medium code output
What is printed to the console if a request is made to `/block` when this filter is active?
java
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
class BlockingFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.out.println("BlockingFilter: Intercepting request");
        if (request.getRequestURI().equals("/block")) {
            response.getWriter().write("Request blocked by filter.");
            System.out.println("BlockingFilter: Request was blocked");
            // DO NOT call filterChain.doFilter(request, response);
            return;
        }
        filterChain.doFilter(request, response);
        System.out.println("BlockingFilter: Request processed");
    }
}

@RestController
class BlockedController {
    @GetMapping("/block")
    public String handleBlocked() {
        System.out.println("Controller: This should not be reached");
        return "Blocked";
    }
}
// Assume BlockingFilter is registered for all paths.
Q407 medium code output
What is the output printed to the console when the following Spring Boot `@Service` using `@Value` from `application.properties` is executed? (Assume `application.properties` contains `app.name=MySpringBootApp`, and standard Spring Boot setup.)
java
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;

@Service
class ConfigService {
    @Value("${app.name}")
    private String appName;
    public String getAppName() { return "Application: " + appName; }
}

// In a @SpringBootApplication's CommandLineRunner, after autowiring:
// System.out.println(configService.getAppName());
Q408 medium code output
Assume there is a `ConfigComponent` class that injects a property `@Value("${app.message:Default Message}")`. What does this code print to the console when `testPropertySourceOverride` is executed?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.junit.jupiter.api.Test;

// ConfigComponent (not shown) injects @Value("${app.message:Default Message}")
@SpringBootTest
@TestPropertySource(properties = {"app.message=Overridden by TestPropertySource"})
public class TestPropertySourceTest {

    @Autowired
    private ConfigComponent configComponent;

    @Test
    void testPropertySourceOverride() {
        System.out.println(configComponent.getMessage());
    }
}
Q409 medium code output
What is the HTTP status code returned by the following Spring Boot controller method if a DELETE request is made to `/api/items/1` and `itemService.deleteItem(1L)` throws an `ItemNotFoundException` (which is annotated with `@ResponseStatus(HttpStatus.NOT_FOUND)`)?
java
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

// Assume ItemNotFoundException is a custom exception:
// @ResponseStatus(HttpStatus.NOT_FOUND)
// public class ItemNotFoundException extends RuntimeException {}

@RestController
@RequestMapping("/api/items")
public class ItemController {

    private ItemService itemService;

    // Constructor injected itemService

    @DeleteMapping("/{id}")
    public void deleteItem(@PathVariable Long id) {
        itemService.deleteItem(id);
    }
}
Q410 medium
To conditionally register a bean using `@Bean` only if a specific property (e.g., `my.service.enabled=true`) is present and true in the environment, which annotation should be applied to the `@Bean` method?
Q411 medium code error
Consider the following Spring Boot controller and a Thymeleaf template. If the `User` object passed to the model has a `null` `name` property, what will be the result when `GET /user` is accessed and the `user-profile.html` template attempts to render `th:text="${user.name.toUpperCase()}"`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;

class User {
    private String name;
    public User(String name) { this.name = name; }
    public String getName() { return name; }
}

@Controller
public class UserController {
    @GetMapping("/user")
    public String getUserProfile(Model model) {
        model.addAttribute("user", new User(null)); // User name is null
        return "user-profile"; // Assumes user-profile.html exists
    }
}
Q412 medium code output
What is the output of this code?
java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.CommandLineRunner;

@Component
class MyService {
    public String greet() { return "Hello from MyService!"; }
}

@Component
class MyRunner implements CommandLineRunner {
    @Autowired
    private MyService service;

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

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
Q413 medium code output
If a Feign client call takes longer than the configured read timeout, what will be the exception message printed?
java
import feign.Request;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@Configuration
class TimeoutConfig {
    @Bean
    public Request.Options options() {
        return new Request.Options(1000, 2000); // connectTimeoutMillis, readTimeoutMillis
    }
}

@FeignClient(name = "timeoutService", url = "http://localhost:8088", configuration = TimeoutConfig.class)
interface TimeoutServiceClient {
    @GetMapping("/delay")
    String getDelayedData();
}

public class TestApplication {
    public static void main(String[] args) {
        try {
            // Simulate a read timeout happening (e.g., service takes > 2000ms)
            throw new feign.RetryableException("Read timed out", null, null, null);
        } catch (feign.RetryableException e) {
            System.out.println("Timeout occurred: " + e.getMessage());
        }
    }
}
Q414 medium
Which other Spring annotation is `@Service` a stereotype for?
Q415 medium code output
What is the output of this code snippet, assuming `Product` with `id=1, name='Pencil', price=1.0` exists, and the `updateProduct` method is invoked?
java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;

// Simplified Product entity with only relevant methods
class Product { 
    private Long id; private String name; private double price;
    public Product(Long id, String name, double price) { this.id = id; this.name = name; this.price = price; }
    public Long getId() { return id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public double getPrice() { return price; }
}

interface ProductRepository extends JpaRepository<Product, Long> {}

// Assuming Product and ProductRepository are properly defined and wired
// and 'productRepository' is an injected instance.
// Simulate DB content: Product(id=1, name='Pencil', price=1.0)

public class TestService {
    ProductRepository productRepository;

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

    @Transactional(readOnly = true)
    public String updateProduct(Long id, String newName) {
        Optional<Product> optionalProduct = productRepository.findById(id);
        if (optionalProduct.isPresent()) {
            Product product = optionalProduct.get();
            product.setName(newName);
            // productRepository.save(product); // Explicit save is often omitted for managed entities within transaction
            return "Attempted update product: " + product.getName();
        }
        return "Product not found";
    }
}
// In a conceptual main method or test:
// System.out.println(new TestService(productRepositoryMock).updateProduct(1L, "Pen"));
Q416 medium code output
What is the output when a Spring Boot application attempts to autowire an interface that has multiple `@Service` implementations without specifying which one? (Assume standard Spring Boot setup and necessary imports.)
java
import org.springframework.stereotype.Service;

interface DataProvider { String provide(); }

@Service class ServiceA implements DataProvider { public String provide() { return "Data from A"; } }
@Service class ServiceB implements DataProvider { public String provide() { return "Data from B"; } }

// In a @SpringBootApplication's CommandLineRunner, attempting to autowire:
// @Autowired DataProvider provider;
// System.out.println(provider.provide());
Q417 medium code error
What type of error will occur during Spring Boot application startup?
java
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public interface MyInterface { String getName(); }

@Service("firstImpl")
public class ImplA implements MyInterface {
    @Override public String getName() { return "Impl A"; }
}

@Service
public class ConsumerService {
    @Autowired
    @Qualifier("secondImpl") // This qualifier name does not exist
    private MyInterface myService;
}
Q418 medium code output
What is the expected value of the `name` parameter in the controller's `search` method?
java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;

@WebMvcTest(controllers = TestController.class)
class TestControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    void testGetWithRequestParam() throws Exception {
        mockMvc.perform(get("/api/search").param("name", "productA").param("category", "electronics"))
               .andExpect(content().string("Searching for: productA"));
    }
}

// Assuming TestController has:
// @RestController
// class TestController {
//    @GetMapping("/api/search")
//    public String search(@RequestParam String name, @RequestParam String category) {
//        return "Searching for: " + name;
//    }
// }
Q419 medium code error
What is the expected error when accessing this endpoint with GET /products?page=invalid?
java
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/products")
public class ProductController {

    @GetMapping
    public String getProducts(@RequestParam int page) {
        return "Products page: " + page;
    }
}
Q420 medium code output
What does this code print to the console when run as a Spring Boot application?
java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

interface MessageService { String send(); }

@Component
class EmailService implements MessageService { @Override public String send() { return "Sending email notification."; } }

@Component
@Primary
class SmsService implements MessageService { @Override public String send() { return "Sending SMS notification."; } }

@Component
class NotificationSender implements CommandLineRunner {
    @Autowired
    private MessageService service;
    @Override
    public void run(String... args) { System.out.println(service.send()); }
}

@SpringBootApplication
public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
← Prev 1920212223 Next → Page 21 of 49 · 971 questions