🌱 Spring Boot MCQ Questions – Page 25
Questions 481–500 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsWhat error occurs when accessing `/search/user name` (note the space) with the following controller?
java
import org.springframework.web.bind.annotation.*;
@RestController
public class SearchController {
@GetMapping("/search/{query}")
public String performSearch(@PathVariable String query) {
return "Searching for: " + query;
}
}
When using `@Valid` with `@RequestBody` in a POST controller method, how can you gracefully capture and process validation errors within the method itself?
A specific controller method, when successfully executed, should always return an HTTP 201 Created status. Which annotation can be directly applied to the method to achieve this without using `ResponseEntity`?
Given the Spring Boot controller above, what will be the HTTP response body when a GET request is made to `/search?query=java`?
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 SearchController {
@GetMapping("/search")
public String searchProduct(@RequestParam String query) {
return "Searching for: " + query;
}
}
What is the output after saving two `Category` entities, given the `name` column has a unique constraint?
java
import jakarta.persistence.*;
@Entity
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String name;
public Category() {}
public Category(String name) { this.name = name; }
}
// Assume categoryRepository is injected and available
// Assume transaction context is active
try {
categoryRepository.save(new Category("Electronics"));
categoryRepository.save(new Category("Electronics")); // Attempt to save again with same unique name
System.out.println("Both categories saved successfully.");
} catch (Exception e) {
System.out.println(e.getClass().getName() + ": Unique constraint violation.");
}
To implement custom validation logic for a field or object in a Spring Boot form (e.g., ensuring a field's value meets specific business rules beyond standard JSR-303), what is the most common approach using Bean Validation?
What is the output of this code snippet, assuming `userRepository` contains a `User` with `id=1` and `name="Bob"` and no `User` with `id=99`?
java
public class UserService {
private UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public String getUserNameById(Long id) {
return userRepository.findById(id)
.map(User::getName)
.orElse("User not found");
}
}
// In a test context or main method:
UserService service = new UserService(userRepository);
String name1 = service.getUserNameById(1L);
String name2 = service.getUserNameById(99L);
System.out.println(name1 + ", " + name2);
Consider this code structure. What would be the output?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
@Component class LoggerService { public String log() { return "Log message"; } }
@Component class ReportingService {
@Autowired private LoggerService logger;
public String generateReport() { return "Report: " + logger.log(); }
}
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
var context = SpringApplication.run(DemoApplication.class, args);
var reporter = context.getBean(ReportingService.class);
System.out.println(reporter.generateReport());
}
}
Consider a Spring Boot `@Controller` method designed to render a view. Which of the following is a common return type for such a method to specify the logical view name?
Consider a Spring Boot REST controller with a `@PostMapping("/register")` method that accepts a `@Valid @RequestBody UserRegistrationDto userDto`. What is the HTTP status code and response body content when the following JSON request is sent to `/register`?
`POST /register HTTP/1.1
Content-Type: application/json
{
"username": "David",
"email": "david@example.com",
"age": 28
}`
java
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Email;
import javax.validation.constraints.Min;
public class UserRegistrationDto {
@NotNull(message = "Username must not be null")
private String username;
@NotNull(message = "Email must not be null")
@Email(message = "Email format is invalid")
private String email;
@NotNull(message = "Age must not be null")
@Min(value = 1, message = "Age must be at least 1")
private Integer age;
// Getters and setters are implicitly present
}
To ensure that a new instance of a bean is created every time it is requested from the Spring container, which annotation or attribute would you use?
What error will occur during application startup for this Spring Boot application?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
@RestController
public class ControllerA {
@Autowired ControllerB controllerB;
@GetMapping("/test")
public String test() { return "Controller A"; }
}
@RestController // Intentionally another controller to create circularity
public class ControllerB {
@Autowired ControllerA controllerA;
@GetMapping("/another")
public String another() { return "Controller B"; }
}
What will happen when this Spring Boot application attempts to shut down?
java
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public CleanUpService cleanUpService() {
return new CleanUpService();
}
}
class CleanUpService implements DisposableBean {
@Override
public void destroy() throws Exception {
System.out.println("CleanUpService performing essential cleanup...");
throw new IllegalStateException("Critical cleanup task failed!");
}
}
What is the expected output when this Spring Boot application starts?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
// In com.example.app.main
@SpringBootApplication
@ComponentScan("com.example.app.other") // Explicitly scans 'other' package
public class MainApplication {
public static void main(String[] args) {
var context = SpringApplication.run(MainApplication.class, args);
try {
var service = context.getBean(OtherService.class);
System.out.println(service.message());
} catch (Exception e) {
System.out.println(e.getClass().getSimpleName());
}
}
}
// In com.example.app.other
@Component class OtherService {
public String message() { return "Found in other package!"; }
}
Consider a Spring Boot REST controller with a `@PostMapping("/register")` method that accepts a `@Valid @RequestBody UserRegistrationDto userDto`. What is the HTTP status code and response body content when the following JSON request is sent to `/register`?
`POST /register HTTP/1.1
Content-Type: application/json
{
"username": "Carl",
"email": null,
"age": 22
}`
java
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Email;
import javax.validation.constraints.Min;
public class UserRegistrationDto {
@NotNull(message = "Username must not be null")
private String username;
@NotNull(message = "Email must not be null")
@Email(message = "Email format is invalid")
private String email;
@NotNull(message = "Age must not be null")
@Min(value = 1, message = "Age must be at least 1")
private Integer age;
// Getters and setters are implicitly present
}
Given the Spring Boot application and assuming `src/main/resources/static/data.txt` contains the text 'Hello from resource!', what will be the output when the application is packaged as a JAR and executed?
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.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StreamUtils;
import java.nio.charset.StandardCharsets;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Bean
public CommandLineRunner resourceReader() {
return args -> {
try {
ClassPathResource resource = new ClassPathResource("static/data.txt");
String content = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
System.out.println("Resource Content: " + content);
} catch (Exception e) {
System.err.println("Error reading resource: " + e.getMessage());
}
};
}
}
What error will Spring Boot generate during application startup for this `MyService` class?
java
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
@Service
public class MyService {
@Autowired
private int port; // Error: Cannot autowire primitive 'int'
public String getServiceInfo() {
return "Running on port: " + port;
}
}
What will be the outcome when running this Spring Boot application?
java
public interface DataProcessor {
String process(String data);
}
@Service("csvProcessor")
public class CsvProcessor implements DataProcessor {
@Override
public String process(String data) { return "Processed CSV: " + data; }
}
@Component
public class ReportGenerator {
@Autowired
@Qualifier("jsonProcessor") // No bean named "jsonProcessor"
private DataProcessor processor;
public void generateReport() {
System.out.println(processor.process("sample"));
}
}
What is the output of this Spring Boot application?
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;
class OptionalService { // No @Component annotation
public String say() { return "I am optional."; }
}
@Component
class MyRunner implements CommandLineRunner {
@Autowired(required = false)
private OptionalService service;
@Override
public void run(String... args) {
if (service != null) {
System.out.println("Service is present: " + service.say());
} else {
System.out.println("OptionalService is null.");
}
}
}
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Given the following Spring Boot controller and DTO, and a POST request with `Content-Type: application/json` and body `{"id": "123"}`, what kind of error or output would you expect when `updateProduct` is called?
java
import org.springframework.web.bind.annotation.*;
import lombok.Data;
@Data
class ProductDto {
private String id;
private String name;
}
@RestController
@RequestMapping("/products")
public class ProductController {
@PutMapping
public String updateProduct(@RequestBody ProductDto productDto) {
return "Product updated: " + productDto.getId() + ", " + productDto.getName();
}
}