🌱 Spring Boot MCQ Questions – Page 26

Questions 501–520 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q501 medium code output
What will be the service name registered in Eureka for a Spring Boot application with `@EnableEurekaClient` and the following `application.yml`?
yaml
spring:
  application:
    name: catalog-service-app

server:
  port: 8084

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
Q502 medium code error
A Spring Boot controller method returns a `String` view name. If the Thymeleaf template `myPage.html` has a syntax error like `th:text="${user.name`, what kind of error will occur at runtime?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;

class User { private String name = "Test"; public String getName() { return name; } }

@Controller
public class MyPageController {

    @GetMapping("/mypage")
    public String showMyPage(Model model) {
        model.addAttribute("user", new User());
        return "myPage"; // Assumes myPage.html exists with th:text="${user.name"
    }
}
Q503 medium code output
What does this code print to the console?
java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.CommandLineRunner;

interface GreetingService {
    String greet();
}

@Component("englishService")
class EnglishGreetingService implements GreetingService {
    @Override public String greet() { return "Hello from English!"; }
}

@Component("spanishService")
class SpanishGreetingService implements GreetingService {
    @Override public String greet() { return "Hola from Spanish!"; }
}

@Component
class MyRunner implements CommandLineRunner {
    @Autowired
    @Qualifier("spanishService")
    private GreetingService service;

    @Override
    public void run(String... args) {
        System.out.println(service.greet());
    }
}

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
Q504 medium code output
What is the output when '/api/items' is accessed, if a `NumberFormatException` occurs?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;

@ControllerAdvice
public class ApiExceptionHandler {
    @ExceptionHandler({NullPointerException.class, NumberFormatException.class})
    public ResponseEntity<String> handleCommonErrors(Exception ex) {
        return new ResponseEntity<>("Common API Error: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
    }
}

@RestController
public class ItemController {
    @GetMapping("/api/items")
    public String getItem(@RequestParam String id) {
        Integer.parseInt(id);
        return "Item processed.";
    }
}
Q505 medium code output
If a request is made to `/step1`, what will be printed to the console when the `/step2` endpoint is subsequently processed due to the forward?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;

@Controller
public class WorkflowController {

    @GetMapping("/step1")
    public String stepOne(Model model) {
        model.addAttribute("step", "One");
        return "forward:/step2";
    }

    @GetMapping("/step2")
    public String stepTwo(Model model) {
        System.out.println("Model attributes in /step2: " + model.asMap().keySet());
        return "stepTwoView";
    }
}
Q506 medium code error
What kind of error will occur when this Spring Boot code snippet is compiled?
java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

public class ResponseEntityTest {
    public ResponseEntity<String> createResponse() {
        String data = "Hello World";
        return ResponseEntity.status(HttpStatus.CREATED).body(data);
    }
}
Q507 medium code error
What error will Spring Boot raise at runtime if a controller method is defined with multiple `@RequestBody` parameters as shown?
java
package com.example.demo;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

@RestController
public class MultiBodyController {
    @PostMapping("/process")
    public ResponseEntity<String> processMultipleBodies(
            @RequestBody Item item1, 
            @RequestBody AnotherItem item2) {
        return ResponseEntity.ok("Processed.");
    }
}
// Item and AnotherItem are simple DTOs with default constructors.
Q508 medium
A Spring Boot POST endpoint needs to ensure it only processes requests where the client sends data in JSON format. Which attribute of the `@PostMapping` annotation should be used for this requirement?
Q509 medium
What is the primary benefit of returning a `ResponseEntity<?>` object from a Spring Boot GET request handler method instead of just a plain object (POJO)?
Q510 medium
In a Spring Boot `@Controller`, what is the primary way to pass data from the handler method to the view?
Q511 medium code output
What is the output of this code?
java
package com.example;

import org.springframework.stereotype.Component; // Changed from @Repository
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;

// Simulate a Hibernate exception class
class ConstraintViolationException extends org.hibernate.exception.ConstraintViolationException {
    public ConstraintViolationException(String message, Throwable cause, String constraintName) {
        super(message, cause, constraintName);
    }
}

@Component // Changed from @Repository
class ProductRepository {
    public void save(String name) {
        throw new ConstraintViolationException("Duplicate key error", null, "uk_product_name");
    }
}

@Service
class ProductService {
    @Autowired ProductRepository repo;
    public void addProduct(String name) {
        try {
            repo.save(name);
        } 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);
        ProductService service = context.getBean(ProductService.class);
        service.addProduct("test");
        context.close();
    }
}
Q512 medium code output
What does this code print?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
@SpringBootApplication
public class MyApplication {
    static class MyCounter { private int count = 0; public int incrementAndGet() { return ++count; } }
    @Bean @Scope("prototype")
    public MyCounter prototypeCounter() { return new MyCounter(); }

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(MyApplication.class, args);
        MyCounter c1 = ctx.getBean(MyCounter.class);
        MyCounter c2 = ctx.getBean(MyCounter.class);
        System.out.println("C1: " + c1.incrementAndGet());
        System.out.println("C2: " + c2.incrementAndGet());
    }
}
Q513 medium code output
What is the output of this code snippet if a client sends a POST request to `/api/users` with the JSON body `{"name": "Frank", "email": "frank@example.com"}`?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

// Assume UserRepository and User entity exist (with auto-gen ID)
@RestController
@RequestMapping("/api/users")
public class UserController {
    private UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        User savedUser = userRepository.save(user);
        return new ResponseEntity<>(savedUser, HttpStatus.CREATED);
    }
}

// Assume the saved user gets id=1.
Q514 medium code output
What is the output printed to the console when the following Spring Boot `@Service` with a `@PostConstruct` method and its usage are executed? (Assume standard Spring Boot application setup and necessary imports.)
java
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;

@Service
class InitService {
    private String status = "Not Initialized";
    @PostConstruct
    public void init() {
        status = "Service Initialized";
    }
    public String getStatus() { return status; }
}

// In a @SpringBootApplication's CommandLineRunner, after autowiring:
// System.out.println(initService.getStatus());
Q515 medium code error
An application uses the above `SettingsController` but forgets to include `spring-boot-starter-validation` in its `pom.xml`. What error will occur when a PUT request is made to `/api/settings/1` with an invalid `Setting` object?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;

@RestController
@RequestMapping("/api/settings")
public class SettingsController {

    @PutMapping("/{id}")
    public ResponseEntity<Setting> updateSetting(@PathVariable Long id, @Valid @RequestBody Setting setting) {
        // Assume logic to find and update setting
        return ResponseEntity.ok(setting);
    }
}

class Setting { // Assume this class exists with some @NotNull etc. annotations
    // ... fields and getters/setters ...
}
Q516 medium code output
What is the output of this code snippet, focusing on the HTTP status and body if a client makes a GET request to `/api/users/100`?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

// Assume UserRepository and User entity exist
@RestController
@RequestMapping("/api/users")
public class UserController {
    private UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        return userRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
}

// Assuming userRepository does NOT contain a User with id=100.
Q517 medium
What is the default value of the `required` attribute for `@RequestParam` in Spring Boot?
Q518 medium code output
If a request is made to `/profile` without any `user` parameters, what will be printed to the console?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.ui.Model;

class User {
    private String username = "guest";
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
}

@Controller
public class UserController {

    @GetMapping("/profile")
    public String showProfile(@ModelAttribute User user, Model model) {
        System.out.println("Model attributes in /profile: " + model.asMap().keySet());
        return "userProfile";
    }
}
Q519 medium code error
What error will occur during application startup for the following controller?
java
import org.springframework.web.bind.annotation.*;

@RestController
public class BrokenController {

    @GetMapping("/invalid-path/{id")
    public String getItem(@PathVariable String id) {
        return "Item: " + id;
    }
}
Q520 medium code output
What is the output of the following Spring Boot application?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
class DatabaseService {
    public String getData() {
        return "Data from DB";
    }
}

@Component
class ReportService {
    @Autowired
    private DatabaseService dbService;

    public void generateReport() {
        System.out.println("Report: " + dbService.getData());
    }
}

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        var context = SpringApplication.run(MyApplication.class, args);
        ReportService reportService = context.getBean(ReportService.class);
        reportService.generateReport();
    }
}
← Prev 2425262728 Next → Page 26 of 49 · 971 questions