🌱 Spring Boot MCQ Questions – Page 10

Questions 181–200 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q181 medium
What type of exceptions does Spring's `@Repository` annotation primarily aim to translate?
Q182 medium
How can you specify that a path variable's name in the URI template is different from the method parameter name in Spring Boot?
Q183 medium code error
What error will occur when Spring attempts to process `StaticAutowiredComponent`?
java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@Component
class SomeDependency { }

@Component
public class StaticAutowiredComponent {
    @Autowired
    private static SomeDependency dependency;

    public static SomeDependency getDependency() {
        return dependency;
    }
}
Q184 medium
Which Spring Boot annotation is primarily used to map HTTP GET requests to a specific handler method in a REST controller?
Q185 medium code output
What is the expected output when the following Spring Boot application runs?
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.context.annotation.Primary;

interface NotificationService {
    String send();
}

@Component
class EmailService implements NotificationService {
    @Override
    public String send() {
        return "Email notification sent.";
    }
}

@Primary
@Component
class SMSService implements NotificationService {
    @Override
    public String send() {
        return "SMS notification sent.";
    }
}

@Component
class UserService {
    private final NotificationService notificationService;

    @Autowired
    public UserService(NotificationService notificationService) {
        this.notificationService = notificationService;
    }

    public void notifyUser() {
        System.out.println("User notified: " + notificationService.send());
    }
}

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        var context = SpringApplication.run(MyApplication.class, args);
        UserService userService = context.getBean(UserService.class);
        userService.notifyUser();
    }
}
Q186 medium code output
Consider a PUT request to `/api/settings/global` with the JSON body `{"theme": "dark", "language": "en"}`. What HTTP status and response body will be returned?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

// Assume Setting class has String key, String value, and constructors/getters/setters.
// Assume GlobalSettingsManager is a component with methods to get/update settings.

class GlobalSettingsManager {
    private String theme = "light";
    private String language = "es";

    public Setting getSetting(String key) {
        if ("theme".equals(key)) return new Setting("theme", theme);
        if ("language".equals(key)) return new Setting("language", language);
        return null;
    }

    public Setting updateSetting(Setting setting) {
        if ("theme".equals(setting.getKey())) { this.theme = setting.getValue(); return setting; }
        if ("language".equals(setting.getKey())) { this.language = setting.getValue(); return setting; }
        return null;
    }
}

@RestController
@RequestMapping("/api/settings")
public class SettingsController {
    private GlobalSettingsManager settingsManager = new GlobalSettingsManager();

    @PutMapping("/{key}")
    public ResponseEntity<Setting> updateSetting(@PathVariable String key, @RequestBody Setting settingDetails) {
        if (!key.equals(settingDetails.getKey())) {
            return ResponseEntity.badRequest().build();
        }
        Setting updatedSetting = settingsManager.updateSetting(settingDetails);
        if (updatedSetting != null) {
            return ResponseEntity.ok(updatedSetting);
        }
        return ResponseEntity.notFound().build();
    }
}
Q187 medium code output
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.context.annotation.Bean;
import org.springframework.boot.CommandLineRunner;

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

    @Bean
    public String myBean() {
        return "Hello from Bean!";
    }

    @Bean
    public CommandLineRunner runner(String myBean) {
        return args -> {
            System.out.println(myBean);
        };
    }
}
Q188 medium
Which of the following is NOT a typical effect of placing `@SpringBootApplication` on a class?
Q189 medium code error
A client sends a PUT request to `/api/users/123` with a valid JSON body. What error will Spring Boot generate at runtime when processing this request?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @PutMapping("/{userId}")
    public ResponseEntity<User> updateUser(@PathVariable("id") Long userId, @RequestBody User userDetails) {
        // Logic to update user
        return ResponseEntity.ok(userDetails);
    }
}
// Assume User class exists
Q190 medium code output
Consider a `Task` entity with a `@Column(length = 20)` constraint. What happens when a task description longer than 20 characters is saved?
java
import jakarta.persistence.*;

@Entity
public class Task {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(length = 20)
    private String description;

    public Task() {}
    public Task(String description) { this.description = description; }
}

// Assume taskRepository is injected and available
// Assume transaction context is active
try {
    String longDescription = "This is a very long description for a task that should exceed twenty characters.";
    Task task = new Task(longDescription);
    taskRepository.save(task);
    System.out.println("Task saved successfully with ID: " + task.getId());
} catch (Exception e) {
    System.out.println(e.getClass().getName() + ": " + e.getMessage());
}
Q191 medium code error
What error will occur when a client makes a DELETE request to `/api/users/123` with the provided code?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private UserService userService; // Assume injected

    @DeleteMapping("/{userId}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return ResponseEntity.noContent().build();
    }
}
Q192 medium code error
What will be the outcome when running this Spring Boot application?
java
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.Primary;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

public interface PaymentGateway {
    String pay();
}

@Service("paypal")
@Primary // This is the primary bean
public class PayPalGateway implements PaymentGateway {
    @Override public String pay() { return "Paying via PayPal"; }
}

@Service("stripe")
public class StripeGateway implements PaymentGateway {
    @Override public String pay() { return "Paying via Stripe"; }
}

@Component
public class PaymentProcessor {
    @Autowired
    @Qualifier("applePay") // No bean named "applePay"
    private PaymentGateway gateway;

    public void processPayment() {
        System.out.println(gateway.pay());
    }
}
Q193 medium code output
A Spring Boot application is configured to use an active profile `dev` in its `application.properties`. When deploying with the following `docker-compose.yml`, which profile will be active in the running Spring Boot application?
yaml
version: '3.8'
services:
  myapp:
    image: my-spring-boot-image
    environment:
      - SPRING_PROFILES_ACTIVE=docker
    ports:
      - "8080:8080"
Q194 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 java.util.List;

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

    public Product() {}
    public Product(Long id, String name, double price) { this.id = id; this.name = name; this.price = price; }
    public String getName() { return name; }
    public double getPrice() { return price; }
}

interface ProductRepository extends JpaRepository<Product, Long> {
    @Query(value = "SELECT name, price FROM product ORDER BY price DESC", nativeQuery = true)
    List<Object[]> findNameAndPriceProjectionNative();
}

// Assume ProductRepository is autowired as 'productRepository'
// And the database contains:
// Product(id=1, name='Desk', price=150.00)
// Product(id=2, name='Chair', price=50.00)
// Product(id=3, name='Lamp', price=30.00)
// Assume 'product' is the correct table name.
List<Object[]> results = productRepository.findNameAndPriceProjectionNative();
System.out.println(results.get(0)[0] + " is " + results.get(1)[1]);
Q195 medium code error
What error will occur when Spring tries to initialize the `MyService` bean?
java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@Component
public class MyService {
    private String dependency;

    public MyService() {
        this.dependency = "Default";
    }

    // Spring will try to satisfy this constructor, but no String bean exists by default
    public MyService(String configValue) {
        this.dependency = configValue;
    }

    public String getConfig() { return dependency; }
}
Q196 medium
How does the `ApplicationContext` interact with Spring Boot's auto-configuration mechanism?
Q197 medium code output
Given the `UserDetails` class (with `email` property) below, what is the HTTP response body when a GET request is made to '/user/details'?
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;

// Assuming UserDetails class is defined as: class UserDetails { private String email; public UserDetails(String email) { this.email = email; } public String getEmail() { return email; } }

@RestController
public class UserDetailsController {
    @GetMapping("/user/details")
    public ResponseEntity<UserDetails> retrieveUserDetails() {
        return new ResponseEntity<>(new UserDetails("test@example.com"), HttpStatus.CREATED);
    }
}
Q198 medium code output
What is the output of this code snippet, demonstrating Feign's `@RequestHeader` annotation usage?
java
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;

@FeignClient(name = "headerService", url = "http://localhost:8084")
interface HeaderServiceClient {
    @GetMapping("/echo-header")
    String echoCustomHeader(@RequestHeader("X-Custom-Header") String customHeader);
}

public class TestApplication {
    public static void main(String[] args) {
        HeaderServiceClient client = header -> "Echoed Header: " + header; // Mock implementation
        System.out.println(client.echoCustomHeader("MyValue123"));
    }
}
Q199 medium code output
Given the Spring Boot controller method below, what HTTP status code and body would be returned if a DELETE request is made to `/api/products/123` and the `productService.deleteProduct` method successfully removes the product?
java
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

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

    private ProductService productService;

    // Constructor injected productService

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteProduct(@PathVariable Long id) {
        productService.deleteProduct(id);
    }
}
Q200 medium code output
Assume there is a `MyComponent` class with a `@PostConstruct` method that sets its internal message. What does this code print to the console when the `contextLoadsAndComponentIsAutowired` test method is executed?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.jupiter.api.Test;

// MyComponent (not shown) is a @Component with getMessage() and @PostConstruct setting message to 'Component Initialized'
@SpringBootTest
public class SpringBootTestContextTest {

    @Autowired
    private MyComponent myComponent;

    @Test
    void contextLoadsAndComponentIsAutowired() {
        System.out.println(myComponent.getMessage());
    }
}
← Prev 89101112 Next → Page 10 of 49 · 971 questions