🌱 Spring Boot MCQ Questions – Page 38
Questions 741–760 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsA Spring Boot application with `@EnableEurekaClient` and default configuration is running. Which of the following is the default health check URL that Eureka registers for this service?
java
@SpringBootApplication
@EnableEurekaClient
public class MyClientApplication {
public static void main(String[] args) {
SpringApplication.run(MyClientApplication.class, args);
}
}
What will be the outcome when running this Spring Boot application?
java
import java.lang.annotation.*;
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomTag {} // Missing @Qualifier meta-annotation
public interface Renderer {
String render();
}
@Service @MyCustomTag
public class HtmlRenderer implements Renderer {
@Override public String render() { return "<html>"; }
}
@Service
public class MarkdownRenderer implements Renderer {
@Override public String render() { return "# Markdown"; }
}
@Component
public class ViewEngine {
@Autowired
@MyCustomTag // This won't work as a qualifier
private Renderer renderer;
public void display() {
System.out.println(renderer.render());
}
}
Consider a utility function designed to extract a JWT from an HTTP 'Authorization' header. What will be the output if the header value is just "TOKEN_STRING" without the "Bearer " prefix?
java
public class JwtHeaderParser {
public static String extractJwtFromHeader(String authorizationHeader) {
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
return authorizationHeader.substring(7);
}
return null;
}
public static void main(String[] args) {
String headerValue = "TOKEN_STRING_123";
String jwt = extractJwtFromHeader(headerValue);
System.out.println(jwt != null ? jwt : "No JWT found");
}
}
What error will occur during application startup for the following configuration?
java
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class DataController {
@GetMapping("/data")
public String getDataA() { return "Data A"; }
@GetMapping("/data")
public String getDataB() { return "Data B"; }
}
When a method in a `@RestController` returns a Java object (e.g., a `User` object), how is the response typically handled by default?
What is the output of this code when the `main` method of `MyApplication` is executed? (Ignore standard Spring Boot logging for this question)
java
// src/main/java/com/example/mainapp/MyApplication.java
package com.example.mainapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
@ComponentScan(basePackages = {"com.example.mainapp", "com.example.other"})
public class MyApplication {
@Autowired
private MyService myService;
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Bean
public CommandLineRunner run() {
return args -> System.out.println("Application Started");
}
}
// src/main/java/com/example/other/MyService.java
package com.example.other;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
@Service
public class MyService {
@PostConstruct
public void init() {
System.out.println("MyService Initialized from other package");
}
}
This application lacks `@Controller` or `@RestController` annotations on the `HomeController` class. What will happen when a client attempts to access `/api/home`?
java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
// Missing @RestController or @Controller annotation
@RequestMapping("/api")
public class HomeController {
@GetMapping("/home")
public String home() {
return "Welcome to home!";
}
}
The `@Repository` annotation is itself meta-annotated with which fundamental Spring stereotype annotation?
Consider the following Spring Boot configuration. What error will be thrown when the ApplicationContext is initialized and attempts to get a bean?
java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
@Configuration
class AppConfig {
@Bean
public String helloBean() {
return "Hello";
}
}
public class TestApp {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
context.getBean("nonExistentBean");
}
}
Which annotation is used to designate a specific bean as the primary choice when multiple beans of the same type are available for autowiring, thus resolving ambiguity?
What error will occur when Spring Boot attempts to start an application containing this `SettingsController`?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/api/settings")
public class SettingsController {
@PutMapping
public ResponseEntity<String> updateSingleSetting(@RequestBody String value) {
return ResponseEntity.ok("Updated single: " + value);
}
@PutMapping
public ResponseEntity<Map<String, String>> updateMultipleSettings(@RequestBody Map<String, String> settings) {
return ResponseEntity.ok(settings);
}
}
Considering the Spring Boot controller method below, and a POST request with `Content-Type: application/json` but a malformed JSON body `{"item":"pencil", "quantity":10,}` (note the trailing comma), what is the expected outcome?
java
import org.springframework.web.bind.annotation.*;
import lombok.Data;
@Data
class ItemDto {
private String item;
private int quantity;
}
@RestController
@RequestMapping("/items")
public class ItemController {
@PostMapping
public String addItem(@RequestBody ItemDto itemDto) {
return "Added: " + itemDto.getItem() + ", Qty: " + itemDto.getQuantity();
}
}
What is the output of this code snippet, assuming a `Product` with `id=1` and `name="Desk"` exists in the database, but no product with `id=99`?
java
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
interface ProductRepository extends JpaRepository<Product, Long> {
}
// Assuming Product and ProductRepository are properly defined and wired
// and 'productRepository' is an injected instance.
// Simulate DB content: Product(id=1, name='Desk', price=500.0)
public class TestService {
ProductRepository productRepository;
public TestService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
public String findProductStatus(Long id) {
return productRepository.findById(id)
.map(p -> "Found: " + p.getName())
.orElse("Not found with ID: " + id);
}
}
// In a conceptual main method or test:
// System.out.println(new TestService(productRepositoryMock).findProductStatus(99L));
What is the printed output when this Spring Boot application is run?
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;
@Component
class InnerService {
public String operation() { return "Inner data"; }
}
@Component
class OuterService {
@Autowired
private InnerService inner;
public String process() { return "Outer processing " + inner.operation(); }
}
@Component
class MyRunner implements CommandLineRunner {
@Autowired
private OuterService outer;
@Override
public void run(String... args) {
System.out.println(outer.process());
}
}
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
What error will be encountered during the application's shutdown process with this configuration?
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean(destroyMethod = "releaseResources") // Method 'releaseResources' does not exist
public ResourceHolder resourceHolder() {
return new ResourceHolder();
}
}
class ResourceHolder {
public void destroy() {
System.out.println("ResourceHolder destroyed.");
}
}
What error will this Spring Boot application throw when the ApplicationContext tries to resolve the autowired dependency, which is then immediately used?
java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
// No MyOptionalService bean defined anywhere
class MyOptionalService { public void doWork() {} }
@Component
class ClientComponent {
@Autowired(required = false)
private MyOptionalService service;
public ClientComponent() {
// Attempt to use 'service' which is null during construction
service.doWork(); // This will cause NPE during bean creation
}
}
public class OptionalAutowiredApp {
public static void main(String[] args) {
new AnnotationConfigApplicationContext(OptionalAutowiredApp.class.getPackage().getName());
}
}
What is the expected error when starting this Spring Boot application with two `@Primary` beans of the same type?
java
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
public interface GreetingService { String greet(); }
@Service
@Primary // First primary bean
public class EnglishGreetingService implements GreetingService {
@Override public String greet() { return "Hello!"; }
}
@Service
@Primary // Second primary bean for the same interface
public class SpanishGreetingService implements GreetingService {
@Override public String greet() { return "Hola!"; }
}
@Service
public class GreetingController {
private final GreetingService greetingService;
public GreetingController(GreetingService greetingService) {
this.greetingService = greetingService;
}
}
If a POST request is made to `/data` with a cookie `session=abc`, which target URI will the request be forwarded to?
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("get_route", r -> r.path("/data").and().method("GET")
.uri("http://localhost:8081/get-data"))
.route("post_cookie_route", r -> r.path("/data").and().method("POST")
.and().cookie("session", "abc")
.uri("http://localhost:8082/post-data"))
.build();
}
}
By default, what is the name of a bean registered using the `@Bean` annotation if no explicit name is provided via the `name` or `value` attribute?
Consider the following Spring Boot setup. What error will be encountered when the application tries to retrieve 'innerStringBean'?
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OuterConfig {
@Bean
public InnerConfig innerConfigBean() {
return new InnerConfig(); // Returns an instance of InnerConfig
}
@Configuration
public static class InnerConfig {
@Bean
public String innerStringBean() {
return "Inner String";
}
}
}
// Main application class tries to get String bean:
// applicationContext.getBean("innerStringBean", String.class);