🌱 Spring Boot MCQ Questions – Page 34
Questions 661–680 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsOne of the key benefits of using `@Repository` is its ability to perform automatic persistence exception translation. What does this mean for the application developer?
What is the output of the `receiveOptionalData` method if a POST request is sent with an *empty* request body and `Content-Type: application/json`?
java
import org.springframework.web.bind.annotation.*;
import lombok.Data;
@Data
class PayloadDto {
private String data;
}
@RestController
@RequestMapping("/optional")
public class OptionalController {
@PostMapping
public String receiveOptionalData(@RequestBody(required = false) PayloadDto payload) {
if (payload == null) {
return "No payload received.";
} else {
return "Payload data: " + payload.getData();
}
}
}
An unauthenticated user accesses the `/public/info` endpoint. What does this code print?
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authorize -> authorize.requestMatchers("/public/**").permitAll().anyRequest().authenticated())
.formLogin(withDefaults()).csrf(csrf -> csrf.disable());
return http.build();
}
}
@RestController
public class PublicController {
@GetMapping("/public/info")
public String getPublicInfo(Authentication authentication) {
if (authentication != null) {
return "Authenticated: " + authentication.getName();
} else {
return "No authentication";
}
}
}
Which statement accurately describes a key difference between `@Controller` and `@RestController` in Spring Boot?
What is the output of this code?
java
package com.example;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
class CustomApplicationException extends RuntimeException {
public CustomApplicationException(String message) {
super(message);
}
}
// No @Repository, @Component, or @Service annotation
class UtilityComponent {
public void doSomethingRisky() {
throw new CustomApplicationException("A specific application error occurred.");
}
}
@Service
class AppService {
// UtilityComponent is not a Spring bean, so instantiate it manually.
private UtilityComponent utility = new UtilityComponent();
public void performAction() {
try {
utility.doSomethingRisky();
} catch (Exception e) {
System.out.println("Caught exception in service: " + e.getClass().getSimpleName());
}
}
}
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
AppService service = context.getBean(AppService.class);
service.performAction();
context.close();
}
}
What error will occur when accessing `/api/find?query=test` with the following Spring Boot controller?
java
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class SearchController {
@GetMapping("/find")
public String findItems(
@RequestParam String query,
@RequestParam(required = true) String category) {
return "Finding " + query + " in " + category;
}
}
Why will this Spring Boot application fail to start successfully?
java
package com.example.app;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;
@SpringBootApplication
public class MyApplication {
// Missing the main method entry point
}
Considering the provided Spring Boot components, what will be the HTTP status code and response body when a GET request is made to `/data/invalid`?
java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
class DataController {
@GetMapping("/data/{value}")
public String getData(@PathVariable String value) {
if ("invalid".equals(value)) throw new IllegalArgumentException("Invalid data value provided");
return "Valid data";
}
}
@RestControllerAdvice
class DataExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArgument(IllegalArgumentException ex) {
return new ResponseEntity<>("Bad Request: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGenericException(Exception ex) {
return new ResponseEntity<>("Unhandled Error: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
What is the HTTP response body when making a GET request to `/path-a`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MultiplePathController {
@GetMapping({"/path-a", "/path-b"})
@ResponseBody
public String handleMultiplePaths() {
return "Handled by common method";
}
}
What is the output of this code snippet, assuming `userRepository` initially contains a `User` with `id=5`?
java
public class UserService {
private UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public String deleteUser(Long id) {
if (userRepository.existsById(id)) {
userRepository.deleteById(id);
return "User " + id + " deleted.";
} else {
return "User " + id + " not found.";
}
}
}
// In a test context or main method:
UserService service = new UserService(userRepository);
String result1 = service.deleteUser(5L);
String result2 = service.deleteUser(5L); // Try to delete again
System.out.println(result1 + "\n" + result2);
A client sends a PUT request to `/api/parameters/limit` with a JSON body `{-10.0}`. What will be the direct HTTP status code and exception type returned by the server, assuming no global `@ExceptionHandler` is configured?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/parameters")
public class ParameterController {
private ParameterService parameterService; // Assume injected
@PutMapping("/{name}")
public ResponseEntity<String> updateParameter(@PathVariable String name, @RequestBody Double newValue) {
if (newValue < 0) {
throw new IllegalArgumentException("Parameter value cannot be negative.");
}
String result = parameterService.updateValue(name, newValue); // Assume this method exists
return ResponseEntity.ok(result);
}
}
// Assume ParameterService exists
In a Spring Boot application, the `@Bean` annotation is typically applied to which of the following?
What does this code print, given the Feign Client interface for uploading a file (simulated with a string) and a call to it?
java
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
@FeignClient(name = "fileUploadService", url = "http://localhost:8086")
interface FileUploadServiceClient {
@PostMapping(value = "/upload", consumes = "multipart/form-data")
String uploadFile(@RequestPart("file") String fileContent, @RequestPart("filename") String filename);
}
public class TestApplication {
public static void main(String[] args) {
FileUploadServiceClient client = (content, name) ->
"Uploaded '" + name + "' with content length: " + content.length();
System.out.println(client.uploadFile("This is file content.", "document.txt"));
}
}
If a client sends a JSON payload `{"id": 1, "value": "test_value"}` to this POST endpoint, what will be the value of `setting.getValue()` inside the `updateSetting` method?
java
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/settings")
public class SettingController {
@PostMapping
public Setting updateSetting(@RequestBody Setting setting) {
System.out.println("Setting value: " + setting.getValue());
return setting;
}
}
class Setting {
private Long id;
@JsonIgnore
private String value;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getValue() { return value; }
public void setValue(String value) { this.value = value; }
}
What is the output of this code?
java
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
@Component
class MyAwareBean implements ApplicationContextAware {
private String status = "Not Aware";
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
status = "Aware of " + applicationContext.getId();
}
public String getStatus() { return status; }
}
@SpringBootApplication
public class App10 {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(App10.class, args);
MyAwareBean bean = ctx.getBean(MyAwareBean.class);
System.out.println(bean.getStatus().split("@")[0]); // Split to remove random hex
}
}
A client sends a GET request to `/api/search?query=test`. What error will the server return for this request?
java
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class SearchController {
@GetMapping("/search")
public String search(@RequestBody String query) {
return "Searching for: " + query;
}
}
Given a global exception handler in `@ControllerAdvice`, what will be the output when '/api/data' is accessed?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
// Assumed: GlobalExceptionHandler.java is in a separate file with @ControllerAdvice
// @ControllerAdvice
// public class GlobalExceptionHandler {
// @ExceptionHandler(IllegalArgumentException.class)
// public ResponseEntity<String> handleIllegalArgument(IllegalArgumentException ex) {
// return new ResponseEntity<>("Global: Invalid input: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
// }
// }
@RestController
public class MyApiController {
@GetMapping("/api/data")
public String getData() {
throw new IllegalArgumentException("ID cannot be negative");
}
}
What is the output when accessing `/welcome` without the `name` parameter?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@RestController
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
@GetMapping("/welcome")
public String welcomeUser(@RequestParam(defaultValue = "Guest") String name) {
return "Welcome, " + name + "!";
}
}
Consider a Spring Boot application running in a Docker container with the following Dockerfile. If you run `docker run -p 9000:8080 my-image`, what port will the Spring Boot application *inside* the container be listening on by default?
dockerfile
FROM openjdk:17-jre-slim
WORKDIR /app
COPY target/my-app.jar app.jar
EXPOSE 8080
CMD ["java", "-jar", "app.jar"]
If a Spring Boot application has two beans of the same type that could satisfy an `@Autowired` dependency, which annotation can be used to specify the preferred bean?