🌱 Spring Boot MCQ Questions – Page 48
Questions 941–960 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsWhat is the main benefit of using Dependency Injection (DI) in Spring Boot applications?
In a typical layered Spring Boot application, where do classes annotated with `@Service` commonly reside?
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("!hasRole('SUPER_ADMIN')")
public String getGeneralContent() { return "General Content"; }
}
public class TestRunner {
public static void main(String[] args) {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("normalUser", "pass", Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")))
);
SecureService service = new SecureService();
try { System.out.println(service.getGeneralContent()); }
catch (Exception e) { System.out.println(e.getClass().getSimpleName()); }
}
}
What is the HTTP status returned by the MockMvc test?
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.status;
@WebMvcTest(controllers = TestController.class)
class TestControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testGetEndpoint() throws Exception {
mockMvc.perform(get("/api/hello"))
.andExpect(status().isOk());
}
}
// Assuming TestController has:
// @RestController
// class TestController {
// @GetMapping("/api/hello")
// public String hello() { return "Hello MockMvc!"; }
// }
Given the controller and a Thymeleaf template `details.html` containing `<p>Value: <span th:text='${data}'></span></p>`, what is the HTTP response body when accessing `/my-details`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class MyDetailsController {
@GetMapping("/my-details")
public ModelAndView showDetails() {
ModelAndView mav = new ModelAndView("details");
mav.addObject("data", "Sample Data");
return mav;
}
}
What is the most likely error when calling this POST endpoint with a JSON request body `{"name": "Laptop", "price": 1200.0}`?
java
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/products")
public class ProductController {
@PostMapping
public String createProduct(Product product) {
return "Product created: " + product.getName();
}
}
class Product {
private String name;
private double price;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
}
What is the primary purpose of the `@RequestBody` annotation in a Spring Boot controller method?
A user named "devuser" with role "DEV" successfully logs in and then accesses the `/profile` endpoint. What does this code print?
java
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
// Assume SecurityConfig and UserDetailsService are configured for a user:
// UserDetails user = User.withUsername("devuser").password("{noop}pass").roles("DEV").build();
// (InMemoryUserDetailsManager initialized with this user)
@RestController
public class ProfileController {
@GetMapping("/profile")
public String getProfile(@AuthenticationPrincipal UserDetails userDetails) {
if (userDetails != null) {
return "Welcome, " + userDetails.getUsername() + "! Your roles: " + userDetails.getAuthorities();
}
return "User not found or not authenticated.";
}
}
What is the primary issue with this `deleteResource` endpoint implementation?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
@RestController
@RequestMapping("/api/resources")
public class ResourceController {
private ResourceService resourceService; // Assume injected
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteResource(@PathVariable Long id) {
// resourceService.delete(id); // Intended call is missing
return ResponseEntity.noContent().build();
}
}
What error occurs when accessing `/items/item123` with the following controller?
java
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/items")
public class ItemController {
@GetMapping("/{itemId}")
public String getItem(String itemId) {
return "Item ID: " + itemId;
}
}
What does this code print to the console?
java
package com.example;
import jakarta.persistence.*;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
@Entity
public class Product {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
public Product() {}
public Product(Long id, String name, double price) { this.id = id; this.name = name; this.price = price; }
public String getName() { return name; }
public double getPrice() { return price; }
}
interface ProductRepository extends JpaRepository<Product, Long> {
@Query("SELECT p FROM Product p WHERE p.id = :productId")
Optional<Product> findProductByIdJPQL(@Param("productId") Long id);
}
// Assume ProductRepository is autowired as 'productRepository'
// And the database contains: Product(id=1, name='Laptop', price=1200.00)
Optional<Product> productOpt = productRepository.findProductByIdJPQL(1L);
System.out.println(productOpt.map(Product::getName).orElse("Not Found"));
What error will the ApplicationContext throw during startup due to conflicting bean definitions?
java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
@Configuration
class ConflictingBeansConfig {
@Bean("myString")
public String stringBeanA() {
return "First";
}
@Bean("myString") // Duplicate bean name
public String stringBeanB() {
return "Second";
}
}
public class ConflictingBeanApp {
public static void main(String[] args) {
new AnnotationConfigApplicationContext(ConflictingBeansConfig.class);
}
}
What is the output of this code when a GET request is made to '/products?name=Laptop'?
java
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProductController {
@RequestMapping("/products")
public String getProductByName(@RequestParam String name) {
return "Product: " + name;
}
}
A user named "john.doe" with role "USER" successfully logs in and then accesses the `/user/details` endpoint. What does this code print?
java
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
// Assume SecurityConfig and UserDetailsService are configured for a user:
// UserDetails user = User.withUsername("john.doe").password("{noop}pass").roles("USER").build();
// (InMemoryUserDetailsManager initialized with this user)
@RestController
public class UserController {
@GetMapping("/user/details")
public String getUserDetails() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
return "Username: " + userDetails.getUsername() + ", Roles: " + userDetails.getAuthorities();
}
return "Not authenticated or principal not UserDetails";
}
}
Given the Spring Boot controller, what is the HTTP status code and response body returned for a PUT request to `/api/items/101` with the JSON body `{"name": "Updated Item A", "description": "A new description for item A"}`?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.Map;
// Assume Item class has Long id, String name, String description, with getters/setters and a constructor.
@RestController
@RequestMapping("/api/items")
public class ItemController {
private Map<Long, Item> items = new HashMap<>();
public ItemController() {
items.put(101L, new Item(101L, "Item A", "Original description A"));
items.put(102L, new Item(102L, "Item B", "Original description B"));
}
@PutMapping("/{id}")
public ResponseEntity<Item> updateItem(@PathVariable Long id, @RequestBody Item itemDetails) {
if (!items.containsKey(id)) {
return ResponseEntity.notFound().build();
}
Item existingItem = items.get(id);
existingItem.setName(itemDetails.getName());
existingItem.setDescription(itemDetails.getDescription());
items.put(id, existingItem);
return ResponseEntity.ok(existingItem);
}
}
What is the consequence if a view named 'dashboard' does not exist in a typical Spring Boot Thymeleaf setup for this controller?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;
@Controller
public class DashboardController {
@GetMapping("/dashboard")
public String showDashboard(Model model) {
model.addAttribute("user", "Admin");
return "dashboard";
}
}
If a request is made to `/send`, what will be printed to the console when the `/receive` endpoint is subsequently processed due to the redirect?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
public class MessageController {
@GetMapping("/send")
public String sendMessage(RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("infoMessage", "Data saved successfully!");
redirectAttributes.addAttribute("queryParam", "value"); // URL parameter
return "redirect:/receive";
}
@GetMapping("/receive")
public String receiveMessage(Model model) {
System.out.println("Model attributes in /receive: " + model.asMap().keySet());
return "displayMessage";
}
}
If the `jackson-dataformat-xml` dependency is *not* present in the classpath, what will happen when a client calls this POST endpoint?
java
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/data")
public class DataController {
@PostMapping(produces = "application/xml")
public MyData createData(@RequestBody MyData data) {
System.out.println("Received data: " + data.getContent());
return data;
}
}
class MyData {
private String content;
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
}
Given `application.properties` does NOT contain `config.value` and the following Java code, what does it print?
java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ConfigService {
@Value("#{'${config.value:default-message}'.length()}")
private int messageLength;
public int getMessageLength() {
return messageLength;
}
}
// In a Spring Boot application, if this component is scanned:
// ConfigService service = applicationContext.getBean(ConfigService.class);
// System.out.println(service.getMessageLength());
In a typical Spring Boot MVC/REST architecture, where should the actual logic for deleting a resource (e.g., calling a JPA repository method) primarily reside?