🌱 Spring Boot MCQ Questions – Page 3
Questions 41–60 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsWhat will be printed to the console when this Spring Boot application runs?
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 RegularService {
public String getName() { return "Regular Service"; }
}
@Component
class StaticAutowiredBean {
@Autowired
private static RegularService service; // Autowiring on a static field is ignored
public String useService() {
return service != null ? service.getName() : "Service is null in static context.";
}
}
@Component
class MyRunner implements CommandLineRunner {
@Autowired
private StaticAutowiredBean bean;
@Override
public void run(String... args) {
System.out.println(bean.useService());
}
}
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
What is the output of this code when the `main` method of `MyApplication` is executed?
java
// src/main/java/com/example/mainapp/MyApplication.java
package com.example.mainapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
// Dummy class in other package to reference
import com.example.other.MyMarkerClass;
@SpringBootApplication
@ComponentScan(basePackageClasses = {MyMarkerClass.class})
public class MyApplication {
@Autowired(required = false)
private MyService myService;
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Bean
public CommandLineRunner run() {
return args -> {
if (myService != null) {
System.out.println("MyService found: " + myService.getMessage());
} else {
System.out.println("MyService not found.");
}
};
}
}
// src/main/java/com/example/other/MyMarkerClass.java
package com.example.other;
// This class is just a marker, not a component itself.
public class MyMarkerClass {}
// src/main/java/com/example/other/MyService.java
package com.example.other;
import org.springframework.stereotype.Service;
@Service
public class MyService {
public String getMessage() {
return "Service initialized from other package.";
}
}
What is the output when accessing `/items?item=apple&item=banana&item=orange`?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.List;
@SpringBootApplication
@RestController
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
@GetMapping("/items")
public String getItems(@RequestParam List<String> item) {
return "Selected items: " + item.toString();
}
}
When are 'Aware' interfaces (e.g., BeanNameAware, BeanFactoryAware) typically called within the Spring bean lifecycle?
What is the HTTP status code and response body when a GET request is sent to `/service/status` given the following Spring Boot code?
java
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
class ServiceUnavailableException extends RuntimeException {
public ServiceUnavailableException(String message) { super(message); }
}
@RestController
class StatusController {
@GetMapping("/service/status")
public String getServiceStatus() {
throw new ServiceUnavailableException("Service is temporarily down");
}
}
@RestControllerAdvice
class CustomErrorHandler {
@ExceptionHandler(ServiceUnavailableException.class)
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
public String handleServiceUnavailable(ServiceUnavailableException ex) {
return "Error: " + ex.getMessage();
}
}
What is the primary use case for `@Value` compared to `@ConfigurationProperties`?
How can you make a `@RequestBody` parameter optional in a Spring Boot controller method?
What is printed to the console when the following Spring Data JPA code is executed?
java
import jakarta.persistence.*;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
public Product() {}
public Product(String name) { this.name = name; }
public Long getId() { return id; }
}
// Assume productRepository is injected and available
// Assume transaction context is active
Product newProduct = new Product("Laptop");
productRepository.save(newProduct);
System.out.println("Product saved with ID: " + newProduct.getId());
What happens when Spring Boot tries to inject 'myService' into 'MyComponent'?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
class MyService {
public String getMessage() { return "Hello"; }
}
@Component
class MyComponent {
@Autowired
private static MyService myService;
public static String getServiceMessage() {
return myService != null ? myService.getMessage() : "Service not injected";
}
}
What is the output printed to the console when a simple `@Service` method is called in a Spring Boot application? (Assume standard Spring Boot application setup and necessary imports.)
java
import org.springframework.stereotype.Service;
@Service
class CalculatorService {
public int add(int a, int b) {
return a + b;
}
}
// In a @SpringBootApplication's CommandLineRunner, after autowiring:
// System.out.println(calculatorService.add(5, 3));
Given the `TestController` and the MockMvc test, what is the output of the test after calling `andDo(print())`?
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.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
@WebMvcTest(controllers = TestController.class)
class TestControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testDebugEndpoint() throws Exception {
mockMvc.perform(get("/debug/info"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string("Debug Info"));
}
}
// Assuming TestController has:
// @RestController
// class TestController {
// @GetMapping("/debug/info")
// public String debugInfo() { return "Debug Info"; }
// }
To automatically deserialize the JSON or XML payload of an HTTP POST request into a Java object parameter in a Spring Boot controller method, which annotation must be used?
What is the HTTP status code and response body for a PUT request to `/api/documents/10` with the JSON body `{"title": "My New Doc"}`?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import java.util.HashMap;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
// Assume Document class has Long id, @NotNull String title, String content.
// And @Valid is enabled globally for Spring Boot.
class Document {
private Long id;
@NotNull
private String title;
private String content;
// Getters, Setters, Constructor
public Document(Long id, String title, String content) { this.id = id; this.title = title; this.content = content; }
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
}
@RestController
@RequestMapping("/api/documents")
public class DocumentController {
private Map<Long, Document> documents = new HashMap<>();
public DocumentController() {
documents.put(10L, new Document(10L, "Old Title", "Some content"));
}
@PutMapping("/{id}")
public ResponseEntity<Document> updateDocument(@PathVariable Long id, @Valid @RequestBody Document docDetails) {
if (!documents.containsKey(id)) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
docDetails.setId(id);
documents.put(id, docDetails);
return ResponseEntity.ok(docDetails);
}
}
What error will be reported when Spring Boot tries to instantiate `MyService`?
java
package com.example.app;
import org.springframework.stereotype.Service;
@Service
public class MyService {
private final int value;
public MyService(int value) {
this.value = value;
}
public String getInfo() {
return "Value: " + value;
}
}
What is the output of this code?
java
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Collections;
public class SecureService {
@PreAuthorize("hasAuthority('ADMIN')")
public String getRestrictedInfo() { return "Restricted Info"; }
}
public class TestRunner {
public static void main(String[] args) {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("admin", "pass", Collections.singletonList(new SimpleGrantedAuthority("ROLE_ADMIN")))
);
SecureService service = new SecureService();
try { System.out.println(service.getRestrictedInfo()); }
catch (Exception e) { System.out.println(e.getClass().getSimpleName()); }
}
}
To handle a specific exception type (e.g., `ResourceNotFoundException`) that might be thrown *within a particular controller*, which annotation would you use on a method inside that controller?
Given `application.properties` contains `app.servers=server1,server2,server3`, how can you inject these values as a `List<String>` into a field?
What is the output of this Spring Boot application?
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;
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(MyApp.class, args);
String message = context.getBean("myGreeting", String.class);
System.out.println(message);
}
}
@Configuration
class AppConfig {
@Bean(name = "myGreeting")
public String greetingBean() {
return "Hello from Spring Boot Bean!";
}
}
When an incoming JSON request body contains fields that are not present in the target Java object (DTO) annotated with `@RequestBody`, what is the default behavior in Spring Boot (using Jackson)?
If a `@RequestParam` is marked as required (either by default or explicitly `required=true`) and the client does not provide the parameter in the request, what HTTP status code will Spring Boot typically return?