🌱 Spring Boot MCQ Questions – Page 31

Questions 601–620 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q601 medium code output
What does this code print to the console?
java
package com.example;

import jakarta.persistence.*;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.Optional;

@Entity
public class Product {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;

    public Product() {}
    public Product(Long id, String name, double price) { this.id = id; this.name = name; this.price = price; }
    public String getName() { return name; }
    public double getPrice() { return price; }
}

interface ProductRepository extends JpaRepository<Product, Long> {
    @Query(value = "SELECT * FROM product WHERE id = :productId", nativeQuery = true)
    Optional<Product> findProductByIdNative(@Param("productId") Long id);
}

// Assume ProductRepository is autowired as 'productRepository'
// And the database contains: Product(id=1, name='Monitor', price=300.00)
// Also, assume 'product' is the correct table name.
Optional<Product> productOpt = productRepository.findProductByIdNative(1L);
System.out.println(productOpt.isPresent() ? productOpt.get().getPrice() : 0.0);
Q602 medium code error
What happens when a client sends a GET request to `/data/123` with this controller configuration, assuming no view 'data/123' exists?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Controller
public class DataViewerController {

    @GetMapping("/data/{id}")
    public Integer getData(@PathVariable int id) {
        return id; 
    }
}
Q603 medium code output
Given this Spring Cloud Gateway configuration, what will be the forwarded URI for an incoming request to `/api/v1/users/123`?
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("user_service_route", r -> r.path("/api/v1/users/**")
                        .filters(f -> f.rewritePath("/api/v1/(?<segment>.*)", "/${segment}"))
                        .uri("http://localhost:8081"))
                .build();
    }
}
Q604 medium code output
What is the HTTP status code returned for a PUT request to `/api/users/1` with the JSON body `{"username": "testuser", "email": "test@example.com"}`?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.Map;

// Assume User class exists with Long id, String username, String email.

@RestController
@RequestMapping("/api/users")
public class UserController {
    private Map<Long, User> users = new HashMap<>();

    public UserController() {
        users.put(1L, new User(1L, "olduser", "old@example.com"));
    }

    @PutMapping("/{id}")
    public ResponseEntity<Void> updateUser(@PathVariable Long id, @RequestBody User userDetails) {
        if (!users.containsKey(id)) {
            return ResponseEntity.notFound().build();
        }
        User existingUser = users.get(id);
        existingUser.setUsername(userDetails.getUsername());
        existingUser.setEmail(userDetails.getEmail());
        users.put(id, existingUser);
        return ResponseEntity.noContent().build();
    }
}
Q605 medium code output
What is the output of this Spring Boot application?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        try {
            ApplicationContext context = SpringApplication.run(MyApp.class, args);
            String preferredMessage = context.getBean(String.class);
            System.out.println(preferredMessage);
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

@Configuration
class AppConfig {
    @Bean
    public String welcomeMessage() { return "Welcome to Spring!"; }

    @Bean
    public String farewellMessage() { return "Goodbye from Spring!"; }
}
Q606 medium
Following a successful form submission via a POST request, what is the recommended Spring MVC approach to prevent duplicate submissions if the user refreshes the page, and to provide a clean URL?
Q607 medium code output
Given the following Spring Boot components, what will be the HTTP status code and response body when a GET request is made to `/products/1`?
java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

class ProductNotFoundException extends RuntimeException {
    public ProductNotFoundException(String message) { super(message); }
}

@RestController
class ProductController {
    @GetMapping("/products/{id}")
    public String getProduct(@PathVariable Long id) {
        if (id == 1) throw new ProductNotFoundException("Product with ID 1 not found");
        return "Product found";
    }
}

@RestControllerAdvice
class GlobalExceptionHandler {
    @ExceptionHandler(ProductNotFoundException.class)
    public ResponseEntity<String> handleProductNotFound(ProductNotFoundException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }
}
Q608 medium code error
What is the expected error when starting this Spring Boot application?
java
import org.springframework.stereotype.Service;

@Service
public class ServiceA {
    private final ServiceB serviceB;

    public ServiceA(ServiceB serviceB) {
        this.serviceB = serviceB;
    }

    public String doSomething() {
        return "A calls B: " + serviceB.execute();
    }
}

// ServiceB is missing @Component/@Service/@Repository annotation
public class ServiceB {
    public String execute() {
        return "ServiceB executed";
    }
}
Q609 medium code error
What kind of error will occur when running the main method of this Spring Boot application?
java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

class MyConfig { // Missing @Configuration/@Component
    @Bean public String someString() { return "Hello"; }
}

@Component
class MyService {
    @Autowired private String someString;
}

public class AppRunner {
    public static void main(String[] args) {
        new AnnotationConfigApplicationContext(AppRunner.class.getPackage().getName());
    }
}
Q610 medium code output
Consider a Spring Boot REST controller with a `@PostMapping("/register")` method that accepts a `@Valid @RequestBody UserRegistrationDto userDto`. What is the HTTP status code and response body content when the following JSON request is sent to `/register`? `POST /register HTTP/1.1 Content-Type: application/json { "username": null, "email": "test@example.com", "age": 30 }`
java
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Email;
import javax.validation.constraints.Min;

public class UserRegistrationDto {
    @NotNull(message = "Username must not be null")
    private String username;

    @NotNull(message = "Email must not be null")
    @Email(message = "Email format is invalid")
    private String email;

    @NotNull(message = "Age must not be null")
    @Min(value = 1, message = "Age must be at least 1")
    private Integer age;

    // Getters and setters are implicitly present
}
Q611 medium
When defining a handler method with `@PathVariable`, what happens if the parameter name in the method signature matches the path variable name in the URI template (e.g., `/items/{id}` and `long id`)?
Q612 medium
Consider two methods mapped with `@RequestMapping("/data")`. One has `produces = "application/json"` and the other has `produces = "application/xml"`. How does Spring Boot decide which method to invoke?
Q613 medium code error
What will be the outcome when a client calls this POST endpoint to create a new `Config` object, for example with a JSON body `{"name": "app.timeout"}`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/configs")
public class ConfigController {
    @PostMapping
    public Config saveConfig(@RequestBody Config newConfig) {
        newConfig.setId(1L);
        return newConfig;
    }
}

class Config {
    private Long id;
    private String name;
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}
Q614 medium
How does Spring Boot typically discover and register classes annotated with `@Repository` as beans in its application context?
Q615 medium code output
What is the HTTP response body when a GET request is made to `/products/123`?
java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProductController {
    @GetMapping("/products/{productId}")
    public String getProductDetails(@PathVariable Long productId) {
        return "Product ID: " + (productId + 100);
    }
}
Q616 medium code error
What error will occur when this Spring Boot application attempts to start?
java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/api/users")
    public String getUserById(@PathVariable("id") String userId) {
        return "User ID: " + userId;
    }
}
Q617 medium code error
A Spring Boot application attempts to define an abstract class `AbstractProductRepository` with the `@Repository` annotation. If `ProductSearchService` tries to `@Autowired` this abstract class without any concrete implementation being a Spring bean, what error will be thrown during application startup?
java
package com.example.repository;
import org.springframework.stereotype.Repository;

@Repository
public abstract class AbstractProductRepository {
    public abstract String getProductName(Long id);
}

package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.repository.AbstractProductRepository;

@Service
public class ProductSearchService {
    @Autowired
    private AbstractProductRepository productRepository;

    public String search(Long id) {
        return productRepository.getProductName(id);
    }
}
// Assuming no concrete class implements AbstractProductRepository and is scanned.
Q618 medium
Which statement about the default scope of a Spring bean in Spring Boot is true?
Q619 medium
To explicitly return an HTTP 204 No Content status from a Spring Boot `@DeleteMapping` method, which `ResponseEntity` configuration is commonly used?
Q620 medium code error
What error will prevent this code from compiling?
java
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMethod;

@RestController
public class MyController {

    @RequestMapping(value = "/api/test", method = RequestMethod.INVALID)
    public String testInvalidMethod() {
        return "This won't work.";
    }
}
← Prev 2930313233 Next → Page 31 of 49 · 971 questions