🌱 Spring Boot MCQ Questions – Page 16
Questions 301–320 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsIf a DELETE request is made to a Spring Boot endpoint for a resource that does not exist, which HTTP status code should typically be returned?
Given the `Order` and `Customer` entities, what happens when `findOrderById` is called and then `getCustomer().getName()` is accessed *outside* an active transaction or persistence context?
java
import jakarta.persistence.*;
@Entity
public class Customer { @Id private Long id; private String name; /* getters, setters */ }
@Entity
@Table(name = "orders")
public class Order {
@Id private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id")
private Customer customer;
/* getters, setters */
}
// Simulate a repository method call outside a transaction
// Assume orderRepository and customerRepository are injected
Order order = orderRepository.findById(1L).orElse(null); // Order exists with customer_id = 1
String customerName = null;
if (order != null) {
customerName = order.getCustomer().getName();
}
System.out.println(customerName);
What is the correct way to inject a property named `server.port` from `application.properties`, providing a default value of `8080` if the property is not found?
What is the expected error when a client sends a GET request to /resource with an Accept header of 'application/xml'?
java
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@RestController
public class ResourceController {
@GetMapping(value = "/resource", produces = MediaType.APPLICATION_JSON_VALUE)
public String getResource() {
return "{ \"data\": \"value\" }";
}
}
Which of the following annotations is often used in combination with `@Qualifier` to enable dependency injection based on a specific bean name or identifier?
What occurs when the `/hello` endpoint is accessed, and a specific view named 'welcome.html' is expected for a Thymeleaf application?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class GreetingController {
@GetMapping("/hello")
public void showHelloPage() {
// Logic here
}
}
Which attributes of the `@Bean` annotation allow you to explicitly specify custom initialization and destruction methods for the bean it produces?
What will be printed to the console when this Spring Boot application runs?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Lazy;
@Component @Lazy class LazyService {
public LazyService() { System.out.println("LazyService initialized."); }
public String serve() { return "Lazy data"; }
}
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
System.out.println("Application Started.");
// LazyService bean is NOT retrieved here
}
}
Given a Spring Boot application with Thymeleaf, what is the most likely error if the following controller code is executed and a request is made to `/hello`, assuming no file named `nonExistentTemplate.html` exists in `src/main/resources/templates/`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;
@Controller
public class MyController {
@GetMapping("/hello")
public String sayHello(Model model) {
model.addAttribute("message", "Hello World!");
return "nonExistentTemplate";
}
}
What error will likely occur when this Spring Boot application attempts to start, assuming `spring-boot-starter-web` is on the classpath?
java
package com.example.app;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootApplication
public class WebConfigApp {
public static void main(String[] args) {
SpringApplication.run(WebConfigApp.class, args);
}
@Configuration
static class MyWebConfig {
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {};
}
}
}
What does this code print to the console when run as a Spring Boot application?
java
import org.springframework.stereotype.Component;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@Component
class SingletonBean { public SingletonBean() { System.out.println("SingletonBean instantiated."); } }
@SpringBootApplication
public class App {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(App.class, args);
SingletonBean bean1 = context.getBean(SingletonBean.class);
SingletonBean bean2 = context.getBean(SingletonBean.class);
System.out.println(bean1 == bean2);
}
}
What error will occur when Spring Boot tries to start the application?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
class ReportingService {
public String generateReport() { return "Report"; }
}
@Component
class ReportConsumer {
@Autowired
@Qualifier("nonExistentQualifier")
private ReportingService service;
}
In a Spring Security context, if an `Authentication` object is stored in `SecurityContextHolder`, what would this code snippet print?
java
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import java.util.Collections;
public class SecurityContextDemo {
public static void main(String[] args) {
// Simulate successful JWT authentication
Authentication auth = new UsernamePasswordAuthenticationToken("jwtUser", null, Collections.emptyList());
SecurityContextHolder.getContext().setAuthentication(auth);
// Retrieve and print principal name
Authentication currentAuth = SecurityContextHolder.getContext().getAuthentication();
if (currentAuth != null) {
System.out.println(currentAuth.getName());
} else {
System.out.println("No authentication found");
}
}
}
What is the HTTP status code and the 'Location' header value returned by this Spring Boot controller method?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.net.URI;
@RestController
public class MyController {
@PostMapping("/create")
public ResponseEntity<Void> createResource() {
return ResponseEntity.created(URI.create("/api/resource/1")).build();
}
}
What is the output of this code snippet configuring Feign client logging?
java
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.cloud.openfeign.FeignClient;
@Configuration
class FeignConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.HEADERS;
}
}
@FeignClient(name = "logService", url = "http://localhost:8087", configuration = FeignConfig.class)
interface LogServiceClient {
String dummyCall();
}
public class TestApplication {
public static void main(String[] args) {
// Assuming FeignConfig is loaded and applied
Logger.Level configuredLevel = new FeignConfig().feignLoggerLevel();
System.out.println("Feign logging level set to: " + configuredLevel.name());
}
}
Consider a Spring Boot application with `@EnableEurekaClient`. If its `application.yml` contains the following configuration, what will be the typical log output during startup related to Eureka client connectivity?
yaml
spring:
application:
name: my-service
server:
port: 8080
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8762/eureka/
Given the following Spring Boot controller and DTO, and a POST request with `Content-Type: application/json` and body `{"name": "Alice", "age": 30}`, what will be the output (return value) of the `createUser` method?
java
import org.springframework.web.bind.annotation.*;
import lombok.Data;
@Data
class UserDto {
private String name;
private int age;
}
@RestController
@RequestMapping("/users")
public class UserController {
@PostMapping
public String createUser(@RequestBody UserDto userDto) {
return "User received: " + userDto.getName() + ", " + userDto.getAge();
}
}
Considering only `MainRunner.main()` is executed, why might a `@RestController` defined in `MyApplication` not be detected?
java
package com.example.app;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
class MyApplication {
// Rest Controller methods
}
class MainRunner {
public static void main(String[] args) {
SpringApplication.run(MainRunner.class, args);
}
}
What is the HTTP status returned by the `createTask` method when a POST request is made to `/tasks` with the JSON body `{"description": "ab"}` (Content-Type: application/json)?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
class Task {
@NotNull
@Size(min = 3)
private String description;
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
}
@RestController
@RequestMapping("/tasks")
class TaskController {
@PostMapping
public ResponseEntity<String> createTask(@Valid @RequestBody Task task) {
return new ResponseEntity<>("Task created: " + task.getDescription(), HttpStatus.CREATED);
}
}
What will be printed to the console by this Spring Boot application?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
interface DataFormatter {
String format(String data);
}
@Component("csvFormatter")
class CsvFormatter implements DataFormatter {
@Override
public String format(String data) {
return "CSV: " + data;
}
}
@Component("jsonFormatter")
class JsonFormatter implements DataFormatter {
@Override
public String format(String data) {
return "JSON: " + data;
}
}
@Component
class DataProcessor {
private final DataFormatter formatter;
@Autowired
public DataProcessor(@Qualifier("jsonFormatter") DataFormatter formatter) {
this.formatter = formatter;
}
public void process() {
System.out.println(formatter.format("sample_data"));
}
}
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
var context = SpringApplication.run(MyApplication.class, args);
DataProcessor processor = context.getBean(DataProcessor.class);
processor.process();
}
}