🌱 Spring Boot MCQ Questions – Page 38

Questions 741–760 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q741 medium code output
A 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);
    }
}
Q742 medium code error
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());
    }
}
Q743 medium code output
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");
    }
}
Q744 medium code error
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"; }
}
Q745 medium
When a method in a `@RestController` returns a Java object (e.g., a `User` object), how is the response typically handled by default?
Q746 medium code output
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");
    }
}
Q747 medium code error
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!";
    }
}
Q748 medium
The `@Repository` annotation is itself meta-annotated with which fundamental Spring stereotype annotation?
Q749 medium code error
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");
    }
}
Q750 medium
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?
Q751 medium code error
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);
    }
}
Q752 medium code output
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();
    }
}
Q753 medium code output
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));
Q754 medium code output
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);
    }
}
Q755 medium code error
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.");
    }
}
Q756 medium code error
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());
    }
}
Q757 medium code error
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;
    }
}
Q758 medium code output
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();
    }
}
Q759 medium
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?
Q760 medium code error
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);
← Prev 3637383940 Next → Page 38 of 49 · 971 questions