🌱 Spring Boot MCQ Questions – Page 13

Questions 241–260 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q241 medium
How does Spring Boot typically discover and register classes annotated with `@Service` as beans?
Q242 medium code output
What is the approximate output after 65-70 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 CronScheduler {

    private int counter = 0;

    // Runs every minute, at 0 seconds past the minute.
    // E.g., HH:MM:00
    @Scheduled(cron = "0 * * * * *")
    public void runCronTask() {
        System.out.println("Cron Task executed. Counter: " + counter++);
    }
}
Q243 medium
What is the relationship between `Model` and `ModelMap` in Spring MVC?
Q244 medium code output
Given two filters with explicit order, what is the console output for a request to `/api/data`?
java
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
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
@Order(2)
class FilterA extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.out.println("Filter A: Before");
        filterChain.doFilter(request, response);
        System.out.println("Filter A: After");
    }
}

@Component
@Order(1)
class FilterB extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.out.println("Filter B: Before");
        filterChain.doFilter(request, response);
        System.out.println("Filter B: After
");
    }
}

@RestController
class ApiController {
    @GetMapping("/api/data")
    public String getData() {
        System.out.println("Controller: Data served");
        return "Data";
    }
}
Q245 medium code output
What is the HTTP response body when a GET request is made to `/data/all`?
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 DataController {
    @GetMapping("/data/all")
    public String getAllData() {
        return "Retrieving all data.";
    }

    @GetMapping("/data/{id}")
    public String getDataById(@PathVariable String id) {
        return "Retrieving data for ID: " + id;
    }
}
Q246 medium code error
What is the expected outcome when this Spring Boot application starts?
java
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public DataProcessor dataProcessor() {
        return new DataProcessor();
    }
}

class DataProcessor implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        throw new RuntimeException("Failed to initialize DataProcessor!");
    }
}
Q247 medium code output
What is the output of this code when a GET request is made to '/api/v1/status'?
java
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class ApiController {
    @RequestMapping("/v1/status")
    public String getStatusV1() {
        return "API V1 Status OK";
    }
}
Q248 medium
Is the `@Repository` annotation exclusively meant for relational database access (e.g., using JDBC or JPA)?
Q249 medium code output
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 and each execution takes approximately 500ms.
java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class FixedDelayScheduler {

    private int counter = 0;

    @Scheduled(fixedDelay = 1000) // Waits 1 second AFTER previous execution finishes
    public void runFixedDelayTask() throws InterruptedException {
        System.out.println("Fixed Delay Task executed. Counter: " + counter++);
        Thread.sleep(500); // Simulate work
    }
}
Q250 medium code output
What is the output of this code snippet, assuming 'Product' with `id=1, name='Old Laptop', price=800.0` exists, and the `updateProductPrice` method is called within a Spring-managed transaction?
java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

interface ProductRepository extends JpaRepository<Product, Long> {
    @Modifying
    @Query("UPDATE Product p SET p.price = :newPrice WHERE p.name = :productName")
    int updateProductPrice(@Param("productName") String name, @Param("newPrice") double newPrice);
}

// Assuming Product and ProductRepository are properly defined and wired
// and 'productRepository' is an injected instance.

public class TestService {
    ProductRepository productRepository;

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

    @Transactional
    public int performUpdate() {
        return productRepository.updateProductPrice("Old Laptop", 1000.0);
    }
}
// In a conceptual main method or test:
// System.out.println(new TestService(productRepositoryMock).performUpdate());
Q251 medium code output
Given the filter configuration below, what is the console output when a GET request is made to `/api/users`?
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 LoggingFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.out.println("LoggingFilter: Request received for " + request.getRequestURI());
        filterChain.doFilter(request, response);
        System.out.println("LoggingFilter: Request processed for " + request.getRequestURI());
    }
}

@Configuration
class FilterConfig {
    @Bean
    public FilterRegistrationBean<LoggingFilter> loggingFilter() {
        FilterRegistrationBean<LoggingFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new LoggingFilter());
        registrationBean.addUrlPatterns("/api/*"); // Matches /api/users, /api/products etc.
        return registrationBean;
    }
}

@RestController
class UserController {
    @GetMapping("/api/users")
    public String getUsers() {
        System.out.println("Controller: Getting user list");
        return "Users";
    }
}
Q252 medium code error
What error will occur when this Spring Boot application attempts to shut down?
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import jakarta.annotation.PreDestroy;

@Configuration
public class AppConfig {

    @Bean
    public MyCleaner myCleaner() {
        return new MyCleaner();
    }
}

class MyCleaner {
    @PreDestroy
    private static void cleanup() { // @PreDestroy methods cannot be static
        System.out.println("MyCleaner performing cleanup.");
    }
}
Q253 medium code output
Given the Spring Boot controller above, what will be the HTTP response body when a GET request is made to `/report` (without a 'type' parameter)?
java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ReportController {
    @GetMapping("/report")
    public String getReport(@RequestParam(required = false) String type) {
        return "Generating " + (type != null ? type : "full") + " report.";
    }
}
Q254 medium
How can you resolve ambiguity when `@Autowired` attempts to inject a dependency but finds multiple beans of the same type?
Q255 medium code output
What will be the output of executing this Spring Boot application?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@Service class DataService {
    public String getData() { return "Processed Data"; }
}

@Component class DataConsumer {
    @Autowired private DataService service;
    public String consume() { return "Consumer uses: " + service.getData(); }
}

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        var context = SpringApplication.run(DemoApplication.class, args);
        var consumer = context.getBean(DataConsumer.class);
        System.out.println(consumer.consume());
    }
}
Q256 medium code output
Given a Feign client configured with a custom `ErrorDecoder` and a simulated 404 response, what is the output?
java
import feign.codec.ErrorDecoder;
import feign.Response;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

class CustomErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        if (response.status() == 404) {
            return new RuntimeException("Resource not found via Feign.");
        }
        return new Default().decode(methodKey, response);
    }
}

@FeignClient(name = "dataService", url = "http://localhost:8082", configuration = CustomErrorDecoder.class)
interface DataServiceClient {
    @GetMapping("/data")
    String getData();
}

public class TestApplication {
    public static void main(String[] args) {
        try {
            DataServiceClient client = () -> { throw new feign.FeignException.NotFound("Mock 404", null, null); };
            System.out.println(client.getData());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
Q257 medium
What is the primary purpose of the `@Qualifier` annotation in Spring Boot when used with `@Autowired`?
Q258 medium code output
What will be the value of the 'id' parameter in the `processId` method if a POST request is made to `/process/item` with a form body 'item_id=100'?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class ItemController {
    @PostMapping("/process/item")
    public String processId(@RequestParam(name = "item_id") int id) {
        // id is used here
        return "item_view";
    }
}
Q259 medium code output
What is the expected header value for 'X-Custom-Header' in the response?
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.header;

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

    @Test
    void testGetWithCustomHeader() throws Exception {
        mockMvc.perform(get("/api/header-test"))
               .andExpect(header().string("X-Custom-Header", "ValueFromController"));
    }
}

// Assuming TestController has:
// @RestController
// class TestController {
//    @GetMapping("/api/header-test")
//    public ResponseEntity<String> headerTest() {
//        return ResponseEntity.ok().header("X-Custom-Header", "ValueFromController").body("OK");
//    }
// }
Q260 medium code output
Assuming a Spring Boot application with a controller as shown, what is the outcome regarding the view and model attributes if a request is made to `/hello`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;

@Controller
public class MyWebController {

    @GetMapping("/hello")
    public String sayHello(Model model) {
        model.addAttribute("name", "World");
        return "greeting";
    }
}
← Prev 1112131415 Next → Page 13 of 49 · 971 questions