🌱 Spring Boot MCQ Questions – Page 47

Questions 921–940 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q921 medium code output
Consider this multi-stage Dockerfile for a Spring Boot application. What will be the *final* command executed when the resulting Docker image is run?
dockerfile
FROM maven:3.8.5-openjdk-17 AS build
WORKDIR /app
COPY pom.xml .
COPY src ./src
RUN mvn package -DskipTests

FROM openjdk:17-jre-slim
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-Dspring.profiles.active=prod", "-jar", "app.jar"]
Q922 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.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@Component
class ServiceA { public String getMessage() { return "ServiceA Message"; } }

@Component
class ClientA implements CommandLineRunner {
    @Autowired
    private ServiceA serviceA;
    @Override
    public void run(String... args) {
        System.out.println(serviceA.getMessage() + " from ClientA");
    }
}

@SpringBootApplication
public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
Q923 medium code output
Given a `MyService` with a `greet()` method that returns "Hello from MyService!", what is the output of this test code?
java
import com.example.demo.service.MyService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import static org.mockito.Mockito.when;

@SpringBootTest
class MyServiceMockTest {
    @MockBean
    MyService myService;

    @Test
    void testMockedService() {
        when(myService.greet()).thenReturn("Mocked Hello!");
        System.out.print(myService.greet());
    }
}
Q924 medium code error
Given the following Spring Boot application setup, what error will occur when the ApplicationContext attempts to initialize and autowire beans?
java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;

interface MyService {}

@Component("myService")
class ServiceA implements MyService {}

@Component("myService")
class ServiceB implements MyService {}

@Configuration
class AppConfig {
    @Autowired
    private MyService service;
}

public class MyApp {
    public static void main(String[] args) {
        new AnnotationConfigApplicationContext(AppConfig.class, ServiceA.class, ServiceB.class);
    }
}
Q925 medium code output
A Spring Boot application is packaged as `app.jar`. The following `Dockerfile` is used. If the container is started with `docker run -m 256m my-image`, what JVM memory setting will likely be applied to the application?
dockerfile
FROM openjdk:17-jre-slim
WORKDIR /app
COPY app.jar .
ENV JAVA_OPTS="-Xms64m -Xmx128m"
CMD ["java", "$JAVA_OPTS", "-jar", "app.jar"]
Q926 medium
When a method annotated with `@Bean` within a standard `@Configuration` class (i.e., `proxyBeanMethods=true`) calls another `@Bean` method in the same class, what is the default behavior of Spring to ensure a singleton instance of the dependency?
Q927 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.context.annotation.Scope;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@Component
@Scope("prototype")
class PrototypeBean { public PrototypeBean() { System.out.println("PrototypeBean instantiated."); } }

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(App.class, args);
        PrototypeBean bean1 = context.getBean(PrototypeBean.class);
        PrototypeBean bean2 = context.getBean(PrototypeBean.class);
        System.out.println(bean1 == bean2);
    }
}
Q928 medium code output
Given the Spring Boot controller above, what will be the HTTP response body when a GET request is made to `/user/101`?
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 UserController {
    @GetMapping("/user/{id}")
    public String getUser(@PathVariable Long id) {
        return "User ID: " + id;
    }
}
Q929 medium code error
What kind of error will occur when the following Spring Boot controller method is compiled?
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;

@RestController
public class MyController {
    @GetMapping("/test")
    public String testEndpoint() {
        return ResponseEntity.status(HttpStatus.OK).body("Success").build();
    }
}
Q930 medium
When designing a DELETE endpoint for a specific resource, how is the resource's unique identifier typically passed from the URL path to the controller method in Spring Boot?
Q931 medium
The `@SpringBootApplication` annotation is a convenience annotation that combines which three Spring annotations?
Q932 medium code error
Given the controller method and an interface `Payload`, what error occurs if a client sends `Content-Type: application/json` and body `{"data": "test"}`?
java
package com.example.demo;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

public interface Payload { String getData(); }

@RestController
public class PayloadController {
    @PostMapping("/payload")
    public ResponseEntity<String> handlePayload(@RequestBody Payload payload) {
        return ResponseEntity.ok("Received: " + payload.getData());
    }
}
// No concrete implementation of Payload is explicitly linked for deserialization.
Q933 medium code output
What is the HTTP status and body returned by the `addComment` method when a POST request is made to `/posts/123/comments` with the JSON body `{"text": "Great post!"}` (Content-Type: application/json)?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

class Comment {
    private String text;
    public String getText() { return text; }
    public void setText(String text) { this.text = text; }
}

@RestController
@RequestMapping("/posts")
class PostController {
    @PostMapping("/{postId}/comments")
    public ResponseEntity<String> addComment(@PathVariable Long postId, @RequestBody Comment comment) {
        return new ResponseEntity<>("Comment '" + comment.getText() + "' added to post " + postId, HttpStatus.CREATED);
    }
}
Q934 medium code error
What is the expected runtime error when making a POST request with a JSON body to this endpoint, if the `UserDTO` is passed without `@RequestBody`?
java
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @PostMapping
    public String createUser(UserDTO user) { // Missing @RequestBody
        return "User created: " + user.getName();
    }
}
// Assume UserDTO exists with public String getName();
// Request: POST /api/users with Content-Type: application/json, Body: {"name": "Alice"}
Q935 medium code output
What is the output of this code snippet, assuming `Order` (id=1) has a `@ManyToOne` relationship with `Customer` (id=10, name='Alice'), and the access to `customer.getName()` occurs outside of an active transaction and without `OpenEntityManagerInViewFilter`?
java
import jakarta.persistence.*;
import org.springframework.data.jpa.repository.JpaRepository;

@Entity
class Customer { @Id private Long id; private String name; /* getters, setters */ public String getName() { return name; } /* other members */ }
@Entity
class Order { @Id private Long id; @ManyToOne @JoinColumn(name = "customer_id") private Customer customer; /* getters, setters */ public Customer getCustomer() { return customer; } /* other members */ }

interface OrderRepository extends JpaRepository<Order, Long> {}

// Assuming Order, Customer, OrderRepository are defined and wired.
// 'orderRepository' is an injected instance.
// Simulate DB content: Order(id=1, customer_id=10); Customer(id=10, name='Alice')

public class TestService {
    OrderRepository orderRepository;

    public TestService(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }

    public String getCustomerNameForOrder(Long orderId) {
        Order order = orderRepository.findById(orderId).orElse(null);
        if (order != null) {
            // This line is executed OUTSIDE a transactional context after 'findById'
            return order.getCustomer().getName(); 
        }
        return "Order not found";
    }
}
// In a conceptual main method or test:
// System.out.println(new TestService(orderRepositoryMock).getCustomerNameForOrder(1L));
Q936 medium code output
Given a Spring Boot application with `@EnableScheduling`, what is the approximate output after 3-4 seconds of the application running, given the following scheduled task? Assume the application starts at T=0.
java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class FixedRateScheduler {

    private int counter = 0;

    @Scheduled(fixedRate = 1000) // Runs every 1 second
    public void runFixedRateTask() {
        System.out.println("Fixed Rate Task executed. Counter: " + counter++);
    }
}
Q937 medium code output
What is the output of this code snippet, assuming `userRepository` initially contains a `User` with `id=7`, and a client makes a DELETE request to `/api/users/7`?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

// Assume UserRepository and User entity exist
@RestController
@RequestMapping("/api/users")
public class UserController {
    private UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteUser(@PathVariable Long id) {
        userRepository.deleteById(id);
    }
}

// Assume `userRepository.deleteById(7L)` is successful.
Q938 medium
How does the destruction lifecycle for a bean with 'prototype' scope differ from a 'singleton' scope bean in Spring?
Q939 medium code output
What does this code print?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
@SpringBootApplication
public class MyApplication {
    interface PaymentGateway { String processPayment(); }
    @Bean public PaymentGateway paypalGateway() { return () -> "Processing payment via PayPal"; }
    @Primary @Bean public PaymentGateway stripeGateway() { return () -> "Processing payment via Stripe (Primary)"; }

    public static void main(String[] args) {
        PaymentGateway gateway = SpringApplication.run(MyApplication.class, args).getBean(PaymentGateway.class);
        System.out.println(gateway.processPayment());
    }
}
Q940 medium
When defining a bean using the `@Bean` annotation within a `@Configuration` class, what happens to the method's return value?
← Prev 4546474849 Next → Page 47 of 49 · 971 questions