🌱 Spring Boot MCQ Questions – Page 44
Questions 861–880 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsA client sends a PUT request to `/api/properties/123` with a JSON body `{"name": "color", "value": "red"}`. What will be the immediate error encountered by the server when processing this request?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/properties")
public class PropertyController {
@PutMapping("/{id}")
public ResponseEntity<String> updateProperty(
@PathVariable Long id,
@RequestParam String name,
@RequestParam String value) {
// Logic to update property with id, name, and value
return ResponseEntity.ok("Property " + id + " updated to " + name + ": " + value);
}
}
A client sends a PUT request to `/api/data/config` with a JSON body `"some_value"`. What error will the server produce when attempting to send the response?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/data")
public class DataController {
@PutMapping("/{key}")
public Object updateData(@PathVariable String key, @RequestBody String value) {
// Imagine some complex data operation
return new Object(); // Returning a generic Object instance
}
}
In Spring Boot, when performing form validation using `@Valid` or `@Validated`, which parameter should immediately follow the validated object in a controller method signature to capture any validation errors?
If the Spring Boot application above is packaged as `myapp.jar` and executed as `java -jar myapp.jar exit`, what will be the final output to the console before the application terminates?
java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(MyApplication.class, args);
if (args.length > 0 && "exit".equals(args[0])) {
SpringApplication.exit(context, () -> 123);
} else {
System.out.println("Application completed normally.");
}
}
@Bean
public CommandLineRunner runner() {
return args -> {
System.out.println("CommandLineRunner executed.");
};
}
}
Considering the Spring Boot application above, if it's packaged as a JAR and executed with `java -jar myapp.jar`, what will be the output from the `CommandLineRunner`?
java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.beans.factory.annotation.Value;
@SpringBootApplication
public class MyApplication {
@Value("${custom.message:Default custom message}")
private String message;
public static void main(String[] args) {
new SpringApplicationBuilder(MyApplication.class)
.properties("custom.message=Message from Builder")
.run(args);
}
@Bean
public CommandLineRunner runner() {
return args -> {
System.out.println("Final Message: " + message);
};
}
}
What is the output of this code?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
@SpringBootApplication
public class MyApplication { // Acting as MyLifecycleBean for conciseness
private String status;
public MyApplication() {
System.out.println("MyApplication: Constructor called.");
this.status = "Initialized by Constructor";
}
@PostConstruct
public void postConstruct() {
System.out.println("MyApplication: @PostConstruct called.");
this.status = "Initialized by PostConstruct";
}
public String getStatus() { return status; }
public static void main(String[] args) {
MyApplication app = SpringApplication.run(MyApplication.class, args).getBean(MyApplication.class);
System.out.println("MyApplication: Status from bean: " + app.getStatus());
}
}
When Spring Boot manages an object through its IoC container, what is that object commonly referred to as?
Given this `application.yml` for a Spring Boot application, what will be observed in the logs regarding its Eureka registration behavior when it starts?
yaml
spring:
application:
name: eureka-server
server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
instance:
hostname: localhost
What is the primary role of the `@Controller` annotation in a Spring Boot MVC application?
What happens if a client sends a POST request to `/submit` for this controller?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class FormController {
@GetMapping("/submit")
@ResponseBody
public String processForm() {
return "Form processed via GET.";
}
}
Given the Spring Boot controller above, what will be the HTTP response body when a GET request is made to `/stats?year=2024`?
java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@RestController
public class StatsController {
@GetMapping("/stats")
public String getStats(@RequestParam Optional<Integer> year) {
return "Statistics for year: " + year.orElse(2023);
}
}
What is the console output if a GET request is made to `/protected` and the `AuthInterceptor` is activated?
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;
@Component
class AuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("AuthInterceptor: Checking credentials...");
// Simulate failed authentication for '/protected'
if (request.getRequestURI().equals("/protected")) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
System.out.println("AuthInterceptor: Authentication failed, stopping chain.");
return false; // Stop further processing
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { System.out.println("AuthInterceptor: Post-handle executed"); }
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { System.out.println("AuthInterceptor: After-completion executed"); }
}
@Configuration
class AuthWebConfig implements WebMvcConfigurer {
private final AuthInterceptor authInterceptor;
public AuthWebConfig(AuthInterceptor authInterceptor) { this.authInterceptor = authInterceptor; }
@Override
public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(authInterceptor).addPathPatterns("/protected"); }
}
@RestController
class ProtectedController {
@GetMapping("/protected")
public String getProtectedData() {
System.out.println("Controller: Accessing protected data");
return "Protected";
}
}
Given the following Spring Boot filter and a simple controller, what will be printed to the console when a request is made to `/test`?
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 javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
@Component
class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("Filter: Before Request");
chain.doFilter(request, response);
System.out.println("Filter: After Request");
}
}
@RestController
class MyController {
@GetMapping("/test")
public String test() {
System.out.println("Controller: Handling Request");
return "OK";
}
}
// Assume FilterRegistrationBean correctly registers MyFilter for all paths.
A `@Repository` class directly uses `EntityManager.persist()` to save an entity. If this method is invoked from a service layer method that is NOT marked `@Transactional` (and no global transaction management is active for that method call), what exception will be thrown when `itemService.createNewItem()` is called?
java
package com.example.entity;
import jakarta.persistence.*;
@Entity public class Item { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; public Item() {} public Item(String name) { this.name = name; } /* getters/setters */ }
package com.example.repository;
import org.springframework.stereotype.Repository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
@Repository
public class ItemRepository {
@PersistenceContext
private EntityManager entityManager;
public void saveItem(Item item) {
entityManager.persist(item); // This requires an active transaction
}
}
package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.repository.ItemRepository;
import com.example.entity.Item;
@Service
public class ItemService {
@Autowired
private ItemRepository itemRepository;
public void createNewItem(String name) {
itemRepository.saveItem(new Item(name)); // Called from a non-transactional context
}
}
// Assuming App main method calls itemService.createNewItem("Laptop"); without @Transactional.
At which stage of the Spring bean lifecycle does a BeanPostProcessor's postProcessAfterInitialization method execute?
Considering the configuration for a `RateLimiter` filter, if a client makes 3 requests to `/rate-limited` within 1 second, what will be the HTTP status code of the 3rd 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("rate_limited_route", r -> r.path("/rate-limited")
.filters(f -> f.requestRateLimiter(c -> c.setRateLimiter(new MyRateLimiter(1, 2))))
.uri("http://localhost:8084"))
.build();
}
// Assume MyRateLimiter is a custom implementation with replenishRate=1, burstCapacity=2
}
What does this code print?
java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.CommandLineRunner;
@Component
class MyService {
public String greet() { return "Constructor Hello!"; }
}
@Component
class MyRunner implements CommandLineRunner {
private final MyService service;
@Autowired
public MyRunner(MyService service) {
this.service = service;
}
@Override
public void run(String... args) {
System.out.println(service.greet());
}
}
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
A client sends a POST request to `/list` with `Content-Type: application/json` and a JSON object body `{"message": "hello"}`. What error will the following controller method encounter?
java
package com.example.demo;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import java.util.List;
@RestController
public class ListController {
@PostMapping("/list")
public ResponseEntity<String> processList(@RequestBody List<String> messages) {
return ResponseEntity.ok("Processed " + messages.size() + " messages.");
}
}
A service needs to publish custom application events to other components within the same Spring Boot application. Which interface, typically provided by the `ApplicationContext`, enables this functionality?
Consider the following Spring Boot component scan setup. What error, if any, will prevent `AnotherService` from being properly injected?
java
package com.example.subpackage;
import org.springframework.stereotype.Service;
@Service
public class AnotherService {
public String getInfo() {
return "Info";
}
}
// In com.example.app package:
// import org.springframework.boot.autoconfigure.SpringBootApplication;
// import org.springframework.context.annotation.ComponentScan;
// @SpringBootApplication
// @ComponentScan(basePackages = "com.example.app")
// public class MainApplication { /* ... */ }
// In MainApplication, a service tries to @Autowired AnotherService