🌱 Spring Boot MCQ Questions – Page 13
Questions 241–260 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsHow does Spring Boot typically discover and register classes annotated with `@Service` as beans?
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++);
}
}
What is the relationship between `Model` and `ModelMap` in Spring MVC?
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";
}
}
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;
}
}
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!");
}
}
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";
}
}
Is the `@Repository` annotation exclusively meant for relational database access (e.g., using JDBC or JPA)?
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
}
}
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());
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";
}
}
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.");
}
}
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.";
}
}
How can you resolve ambiguity when `@Autowired` attempts to inject a dependency but finds multiple beans of the same type?
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());
}
}
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());
}
}
}
What is the primary purpose of the `@Qualifier` annotation in Spring Boot when used with `@Autowired`?
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";
}
}
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");
// }
// }
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";
}
}