🌱 Spring Boot MCQ Questions – Page 40

Questions 781–800 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q781 medium
Consider a class annotated with `@Configuration`. What is the purpose of the `@Bean` annotation within such a class in the context of IoC?
Q782 medium code output
What is the output of this code snippet, assuming a `Product` with `id=1` and `name="Laptop"` exists in the database?
java
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;

interface ProductRepository extends JpaRepository<Product, Long> {
    Optional<Product> findByName(String name);
}

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

public class TestService {
    ProductRepository productRepository;

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

    public String getProductInfo(String name) {
        return productRepository.findByName(name)
                                .map(Product::getName)
                                .orElse("Product Not Found");
    }
}
// In a conceptual main method or test:
// System.out.println(new TestService(productRepositoryMock).getProductInfo("Laptop"));
Q783 medium code output
What is the expected output after attempting to save a `Department` with a new `Employee` and subsequently removing that employee from the list when `orphanRemoval` is enabled?
java
import jakarta.persistence.*;
import java.util.*;

@Entity
public class Department {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
    private String name;
    @OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Employee> employees = new ArrayList<>();
    // ... constructors, getters, add/remove methods
}

@Entity
public class Employee {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
    private String name;
    @ManyToOne @JoinColumn(name = "department_id") private Department department;
    // ... constructors, getters, setters
}

// Assume departmentRepository is injected and available
// Assume transaction context is active
Department dept = new Department("IT");
Employee emp1 = new Employee("Alice");
emp1.setDepartment(dept);
dept.getEmployees().add(emp1);
departmentRepository.save(dept); // Saves dept and emp1

dept.getEmployees().remove(emp1);
departmentRepository.save(dept); // Updates dept
System.out.println("Employee Alice status: " + (departmentRepository.findById(dept.getId()).orElse(new Department()).getEmployees().isEmpty() ? "Removed" : "Present"));
Q784 medium
What is the default behavior of `@PathVariable` regarding its `required` attribute?
Q785 medium code output
What is the HTTP status and JSON body returned by the `addItem` method when a POST request is made to `/items` with the JSON body `{"name": "Book"}` (Content-Type: application/json)?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

class Item {
    private String name;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}

@RestController
@RequestMapping("/items")
class ItemController {
    @PostMapping
    public ResponseEntity<Item> addItem(@RequestBody Item item) {
        item.setName(item.getName() + " Added");
        return new ResponseEntity<>(item, HttpStatus.OK);
    }
}
Q786 medium
If a class is annotated with `@Repository` but no specific persistence framework (like JPA or Spring Data JDBC) is configured in the application, what is the effect of the annotation?
Q787 medium code error
What will be the outcome when trying to access the `/data` endpoint of this Spring Boot application if the intention was to return JSON?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class DataController {

    @GetMapping("/data")
    public MyObject getData() {
        return new MyObject("Test", 123);
    }

    private static class MyObject {
        public String message; public int value;
        public MyObject(String message, int value) { this.message = message; this.value = value; }
    }
}
Q788 medium
In Spring MVC, how do you typically instruct the browser to perform a client-side redirect to a different URL from a controller method?
Q789 medium code output
What is the HTTP response body when a GET request is made to '/greet/Alice'?
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 GreetController {
    @GetMapping("/greet/{name}")
    public String greetUser(@PathVariable String name) {
        return "Greetings, " + name + "!";
    }
}
Q790 medium code output
An incoming request targets `/echo?status=test`. What value will the `X-Status` header contain in the forwarded request?
java
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GatewayConfig {
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("query_header_route", r -> r.path("/echo")
                        .and().query("status")
                        .filters(f -> f.addRequestHeader("X-Status", "{status}"))
                        .uri("http://localhost:8083"))
                .build();
    }
}
Q791 medium code output
What is the HTTP status code and response body for a PUT request to `/api/tasks/5` with the JSON body `{"title": "Updated Task", "completed": true}`?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

// Assume Task class has Long id, String title, boolean completed.

@RestController
@RequestMapping("/api/tasks")
public class TaskController {
    private Map<Long, Task> tasks = new HashMap<>();

    public TaskController() {
        tasks.put(5L, new Task(5L, "Original Task", false));
    }

    @PutMapping("/{id}")
    public ResponseEntity<Task> updateTask(@PathVariable Long id, @RequestBody Task taskUpdate) {
        return Optional.ofNullable(tasks.get(id))
                       .map(existingTask -> {
                           existingTask.setTitle(taskUpdate.getTitle());
                           existingTask.setCompleted(taskUpdate.isCompleted());
                           tasks.put(id, existingTask);
                           return ResponseEntity.ok(existingTask);
                       })
                       .orElse(ResponseEntity.notFound().build());
    }
}
Q792 medium
Once a `ResponseEntity` object has been created (e.g., `ResponseEntity.ok().body(data)`), can its HTTP status code or headers be directly modified?
Q793 medium code output
What is the HTTP response status code and `Location` header value when making a GET request to `/legacy-url`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class RedirectController {

    @GetMapping("/legacy-url")
    public String redirectToNewUrl() {
        return "redirect:/new-url";
    }
}
Q794 medium code output
Given the controller and a Thymeleaf template `product.html` containing `<h1 th:text='${productName}'></h1>`, what is the HTTP response body when accessing `/product-details`?
java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class ProductController {

    @GetMapping("/product-details")
    public String showProductDetails(Model model) {
        model.addAttribute("productName", "Laptop Pro");
        return "product";
    }
}
Q795 medium code error
What will be the outcome when running this Spring Boot application?
java
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

public interface Theme {
    String getName();
}

@Service("darkTheme")
public class DarkTheme implements Theme {
    @Override public String getName() { return "Dark"; }
}

@Service("lightTheme")
public class LightTheme implements Theme {
    @Override public String getName() { return "Light"; }
}

@Component
public class UserSettings {
    private final Theme activeTheme;

    @Autowired // Ambiguous constructor, @Qualifier missing
    public UserSettings(Theme activeTheme) {
        this.activeTheme = activeTheme;
    }

    public String getCurrentTheme() {
        return activeTheme.getName();
    }
}
Q796 medium
According to REST principles, which HTTP method should be used for retrieving resource representations without causing any side effects on the server, ensuring the operation is both safe and idempotent?
Q797 medium code output
If the `ItemServiceClient` fails to connect to the backend service, and a fallback factory is configured, what will be the output?
java
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;

interface ItemServiceClient {
    @GetMapping("/items")
    String getItems();
}

@FeignClient(name = "itemService", url = "http://localhost:8083", fallbackFactory = ItemServiceFallbackFactory.class)
interface ItemServiceClientFeign extends ItemServiceClient {}

@Component
class ItemServiceFallbackFactory implements FallbackFactory<ItemServiceClient> {
    @Override
    public ItemServiceClient create(Throwable cause) {
        return () -> "Fallback: Could not retrieve items due to: " + cause.getClass().getSimpleName();
    }
}

public class TestApplication {
    public static void main(String[] args) {
        ItemServiceFallbackFactory factory = new ItemServiceFallbackFactory();
        ItemServiceClient client = factory.create(new RuntimeException("Connection Refused"));
        System.out.println(client.getItems());
    }
}
Q798 medium code output
What is the output of this Spring Boot application when run without setting the 'app.feature.enabled' property?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;

@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        try {
            ApplicationContext context = SpringApplication.run(MyApp.class, args);
            FeatureService service = context.getBean(FeatureService.class);
            System.out.println(service.getFeatureStatus());
        } catch (NoSuchBeanDefinitionException e) {
            System.out.println("Error: " + e.getBeanType().getName() + " bean not found.");
        } catch (Exception e) {
            System.out.println("An unexpected error occurred: " + e.getMessage());
        }
    }
}

class FeatureService {
    public String getFeatureStatus() { return "Feature is enabled!"; }
}

@Configuration
class AppConfig {
    @Bean
    @ConditionalOnProperty(name = "app.feature.enabled", havingValue = "true", matchIfMissing = false)
    public FeatureService featureService() {
        return new FeatureService();
    }
}
Q799 medium code output
What is the console output when a GET request is made to `/info` in this Spring Boot application with multiple interceptors?
java
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.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Component
class Interceptor1 implements HandlerInterceptor {
    @Override public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) { System.out.println("Int1: pre"); return true; }
    @Override public void postHandle(HttpServletRequest req, HttpServletResponse res, Object handler, ModelAndView mv) { System.out.println("Int1: post"); }
    @Override public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) { System.out.println("Int1: after"); }
}

@Component
class Interceptor2 implements HandlerInterceptor {
    @Override public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) { System.out.println("Int2: pre"); return true; }
    @Override public void postHandle(HttpServletRequest req, HttpServletResponse res, Object handler, ModelAndView mv) { System.out.println("Int2: post"); }
    @Override public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) { System.out.println("Int2: after"); }
}

@Configuration
class MvcConfig implements WebMvcConfigurer {
    private final Interceptor1 int1; private final Interceptor2 int2;
    public MvcConfig(Interceptor1 int1, Interceptor2 int2) { this.int1 = int1; this.int2 = int2; }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(int1).addPathPatterns("/info");
        registry.addInterceptor(int2).addPathPatterns("/info");
    }
}

@RestController
class InfoController {
    @GetMapping("/info")
    public String getInfo() {
        System.out.println("Controller: Showing Info");
        return "Info";
    }
}
Q800 medium code error
A client sends a POST request to `/items` with a JSON body `{"name": "Test Item"}` but sets the `Content-Type` header to `text/plain`. What error will occur with the following 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 3839404142 Next → Page 40 of 49 · 971 questions