🌱 Spring Boot MCQ Questions – Page 32
Questions 621–640 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsWhat is the output when accessing `/calculate?num1=10&num2=20`?
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("/calculate")
public String calculate(@RequestParam int num1, @RequestParam int num2) {
return "Sum: " + (num1 + num2);
}
}
Given the following Spring Boot controller method and assuming a `redirectTarget.html` template exists, what happens to the `message` attribute when a request is made to `/redirectMe`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;
@Controller
public class RedirectController {
@GetMapping("/redirectMe")
public String redirectToTarget(Model model) {
model.addAttribute("message", "Hello from Redirect!");
return "redirect:/target";
}
@GetMapping("/target")
public String redirectTarget(Model model) {
// Assume redirectTarget.html tries to access ${message}
return "redirectTarget";
}
}
In a typical Spring Boot application using Spring Data JPA, where would you most commonly apply the `@Repository` annotation?
What is the output when accessing '/users/{id}' if the `id` is invalid (e.g., negative)?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@RestController
public class UserController {
@GetMapping("/users/{id}")
public String getUser(@PathVariable int id) {
if (id < 0) {
throw new IllegalArgumentException("User ID cannot be negative");
}
return "User " + id + " found.";
}
@ExceptionHandler
public ResponseEntity<String> handleAnyException(Exception ex) {
return new ResponseEntity<>("Caught by generic handler: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Given the controller, if `welcome.html` tries to access `${username}` directly, what will be the outcome when navigating to `/welcome`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.ModelMap;
@Controller
public class WelcomeController {
@GetMapping("/welcome")
public String showWelcome(ModelMap map) {
map.addAttribute("user", "Alice");
return "welcome"; // Assumes welcome.html tries to access ${username}
}
}
What error will prevent this code from compiling?
java
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@RequestMapping(value = "/api/route1", path = "/api/route2")
public String conflictingPaths() {
return "This will fail.";
}
}
What is the output when a Spring Boot application attempts to autowire a `@Service` located outside its default component scan base package? (Assume the `@SpringBootApplication` is in `com.example` and `MyHiddenService` is in `com.example.other`.)
java
import org.springframework.stereotype.Service;
// This class is in package: com.example.other
@Service
class MyHiddenService {
public String getValue() { return "Hidden Value"; }
}
// In a @SpringBootApplication (base package: com.example) CommandLineRunner, after autowiring:
// @Autowired MyHiddenService service;
// System.out.println(service.getValue());
By default, what is the scope of a `@Controller` component when it's managed as a Spring bean in a Spring Boot application?
What is the output of this Spring Boot application?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.PropertySource;
@Component
@PropertySource("classpath:application.properties")
class AppInfo {
@Value("${app.name:DefaultApp}")
private String appName;
@Value("${app.version:1.0}")
private String appVersion;
public void printInfo() {
System.out.println("App Name: " + appName);
System.out.println("App Version: " + appVersion);
}
}
// Assuming application.properties contains:
// app.name=MyWebApp
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
var context = SpringApplication.run(MyApplication.class, args);
AppInfo appInfo = context.getBean(AppInfo.class);
appInfo.printInfo();
}
}
What is the output of the `System.out.println` statement?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component class InitOrderComponent {
private String status = "Initial";
public InitOrderComponent() { status = "Constructor"; }
@PostConstruct public void postConstruct() { status = "PostConstruct"; }
public String getStatus() { return status; }
}
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
var context = SpringApplication.run(DemoApplication.class, args);
var component = context.getBean(InitOrderComponent.class);
System.out.println(component.getStatus());
}
}
If a Spring Boot controller has `@RequestMapping("/api")` at the class level and a method inside it has `@RequestMapping("/users")`, what is the full path to access this method?
To automatically validate the data in an object received via `@RequestBody` based on JSR-303 annotations (like `@NotNull`, `@Size`), which additional annotation should be used on the method parameter?
Can placeholder resolution `${...}` and SpEL `#{...}` be combined within a single `@Value` annotation, and if so, how?
Which statement best describes the relationship between the InitializingBean interface and the @PostConstruct annotation for bean initialization?
What is the HTTP status code and response body when a GET request is made to `/admin/action` if `UnauthorizedAccessException` is thrown, using the provided Spring Boot classes?
java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;
class UnauthorizedAccessException extends RuntimeException {
public UnauthorizedAccessException(String message) { super(message); }
}
@RestController
class AdminController {
@GetMapping("/admin/action")
public String adminAction() {
throw new UnauthorizedAccessException("Access denied for this resource");
}
}
@RestControllerAdvice
class SecurityExceptionHandler {
@ExceptionHandler(UnauthorizedAccessException.class)
public ResponseEntity<Map<String, String>> handleUnauthorized(UnauthorizedAccessException ex, HttpServletRequest request) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(Map.of("error", ex.getMessage(), "path", request.getRequestURI()));
}
}
What is the output of this code?
java
package com.example;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@Repository
class ProductInfoRepository {
public String getProductDetails() {
return "Product: Laptop, Price: $1200";
}
}
@RestController
class ProductController {
@Autowired ProductInfoRepository repo;
@GetMapping("/product")
public String getProduct() {
return repo.getProductDetails();
}
}
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
// Simulate a web request by directly calling the controller method
ProductController controller = context.getBean(ProductController.class);
System.out.println(controller.getProduct());
context.close();
}
}
What is the output when accessing `/greet` 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("/greet")
public String greetUser(@RequestParam String name) {
return "Hello, " + name + "!";
}
}
What would be the effect on a request to `/proxy/my-service/hello` with an original `X-Request-ID` header value of `12345`?
java
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("proxy_route", r -> r.path("/proxy/**")
.filters(f -> f.removeRequestHeader("X-Request-ID"))
.uri("http://localhost:8087"))
.build();
}
}
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('ADMIN')")
public String getAdminData() { return "Admin Data"; }
}
public class TestRunner {
public static void main(String[] args) {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("user", "pass", Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")))
);
SecureService service = new SecureService();
try { System.out.println(service.getAdminData()); }
catch (Exception e) { System.out.println(e.getClass().getSimpleName()); }
}
}
To inject the `JAVA_HOME` environment variable using `@Value`, which of the following is the correct syntax?