🌱 Spring Boot MCQ Questions – Page 30

Questions 581–600 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q581 medium code error
If a PUT request is made to `/api/books/999` where `999` is an ID that does not exist in the database, what will be the immediate runtime error in the `updateBook` method?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;

@RestController
@RequestMapping("/api/books")
public class BookController {
    private BookRepository bookRepository; // Assume injected

    @PutMapping("/{id}")
    public ResponseEntity<Book> updateBook(@PathVariable Long id, @RequestBody Book bookDetails) {
        Optional<Book> existingBookOptional = bookRepository.findById(id);
        Book existingBook = existingBookOptional.get(); // Potential error line
        existingBook.setTitle(bookDetails.getTitle());
        return ResponseEntity.ok(bookRepository.save(existingBook));
    }
}
// Assume Book and BookRepository exist
Q582 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.RestController;

@RestController
public class MyController {

    @GetMapping(value = "/api/resource", params = {"version=1", "version=2"})
    public String getResourceByVersion() {
        return "Resource";
    }
}
Q583 medium code error
What error will occur when calling `/user?id=abc` in this Spring Boot application?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    @GetMapping("/user")
    @ResponseBody
    public String getUserById(@RequestParam("id") int userId) {
        return "User ID: " + userId;
    }
}
Q584 medium code output
Assuming a DTO `Product { public String name; public double price; }` and default JSON serialization, what is the HTTP status and body output?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

class Product {
    public String name = "Laptop";
    public double price = 1200.50;
}

@RestController
public class MyController {
    @GetMapping("/product")
    public ResponseEntity<Product> getProduct() {
        return ResponseEntity.ok(new Product());
    }
}
Q585 medium code error
What is wrong with this Spring Boot DELETE endpoint implementation?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    private ProductService productService; // Assume injected

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(String id) {
        productService.deleteProduct(id);
        return ResponseEntity.noContent().build();
    }
}
Q586 medium code output
Consider a Spring Boot controller with the following method. If a DELETE request is sent to `/api/resources/remove?name=old_resource` and the `resourceService.deleteByName("old_resource")` method successfully deletes exactly one resource, what HTTP status code and body will the client receive?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/resources")
public class ResourceController {

    private ResourceService resourceService;

    // Constructor injected resourceService

    @DeleteMapping("/remove")
    public ResponseEntity<String> deleteResourceByName(@RequestParam String name) {
        boolean deleted = resourceService.deleteByName(name);
        if (deleted) {
            return ResponseEntity.ok("Resource '" + name + "' deleted.");
        } else {
            return ResponseEntity.status(404).body("Resource '" + name + "' not found.");
        }
    }
}
Q587 medium code output
What does this code print to the console when run as a Spring Boot application?
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

class MyService { public String doSomething() { return "MyService created."; } }

@Configuration
class MyConfig { @Bean public MyService myService() { return new MyService(); } }

@Component
class MyRunner implements CommandLineRunner {
    @Autowired
    private MyService service;
    @Override
    public void run(String... args) {
        System.out.println(service.doSomething() + " MyService message from Runner.");
    }
}

@SpringBootApplication
public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
Q588 medium code output
What is the HTTP status code and response body returned by this Spring Boot controller method?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
    @GetMapping("/hello")
    public ResponseEntity<String> sayHello() {
        return ResponseEntity.ok("Hello Spring!");
    }
}
Q589 medium code output
Consider the following Spring Boot application. What will be printed to the console when this application runs?
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 ServiceA {
    public String getMessage() {
        return "Message from ServiceA";
    }
}

@Component
class ServiceB {
    private final ServiceA serviceA;

    @Autowired
    public ServiceB(ServiceA serviceA) {
        this.serviceA = serviceA;
    }

    public void printMessage() {
        System.out.println("ServiceB uses: " + serviceA.getMessage());
    }
}

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        var context = SpringApplication.run(MyApplication.class, args);
        ServiceB serviceB = context.getBean(ServiceB.class);
        serviceB.printMessage();
    }
}
Q590 medium code error
What error will occur when accessing `/api/settings?debug=yes` with the following Spring Boot controller?
java
import org.springframework.web.bind.annotation.*;

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

    @GetMapping("/settings")
    public String getSettings(@RequestParam boolean debug) {
        return "Debug mode: " + debug;
    }
}
Q591 medium
To manually define a bean within a Spring Boot application using Java configuration, what two annotations are typically used together to define a class that contains bean creation methods and the methods themselves, respectively?
Q592 medium
When Thymeleaf is included as a dependency in a Spring Boot project, where does Spring Boot typically expect to find Thymeleaf template files by default?
Q593 medium code error
A Spring Boot application attempts to use `@Repository` with a `PersistenceExceptionTranslationPostProcessor` to translate persistence exceptions. However, no `PlatformTransactionManager` bean is defined or configured. If an exception occurs within a method of `InventoryRepository`, what type of exception will propagate, indicating the translation mechanism is not fully functional?
java
package com.example.dao;
import org.springframework.stereotype.Repository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.hibernate.exception.ConstraintViolationException;

@Repository
public class InventoryRepository {
    @PersistenceContext
    private EntityManager entityManager;

    public void updateStock(Long productId, int quantity) {
        // Simulate a DB write that might cause an error
        // entityManager.merge(product);
        throw new ConstraintViolationException("Stock cannot be negative", null, "STOCK_CONSTRAINT");
    }
}

package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;

@Configuration
public class AppConfig {
    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }
    // MISSING: @Bean PlatformTransactionManager transactionManager(EntityManagerFactory emf) { ... }
}

package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.dao.InventoryRepository;

@Service
public class InventoryService {
    @Autowired
    private InventoryRepository inventoryRepository;

    @Transactional
    public void processUpdate(Long productId, int quantity) {
        inventoryRepository.updateStock(productId, quantity);
    }
}
// Assuming @EnableTransactionManagement is present.
Q594 medium code output
What is the output of this code?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@SpringBootApplication
public class MyApplication {
    @Bean
    public String greetingBean() {
        return "Hello Spring Beans!";
    }
    public static void main(String[] args) {
        String greeting = SpringApplication.run(MyApplication.class, args).getBean("greetingBean", String.class);
        System.out.println(greeting);
    }
}
Q595 medium
In a Spring Boot `@Controller`, how would you typically bind data from an HTML form submission directly into a Java object (e.g., a `User` object)?
Q596 medium
After a form submission with validation errors, which Thymeleaf attribute is commonly used to display error messages associated with a specific field (e.g., for a 'username' field)?
Q597 medium code output
What is the output of this code when a GET request is made to '/greet'?
java
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {
    @RequestMapping("/greet")
    public String sayHello() {
        return "Hello from Spring Boot!";
    }
}
Q598 medium
Which `ResponseEntity` static builder method should you use to return an HTTP 201 (Created) status code with a newly created resource in the response body?
Q599 medium
Can `@Autowired` be used within a `@Configuration` class to inject dependencies into a `@Bean` method that creates another bean?
Q600 medium code error
What is the expected runtime error when accessing this endpoint with GET /users/123?
java
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping("/{userId}")
    public String getUser(@PathVariable String id) {
        return "User ID: " + id;
    }
}
← Prev 2829303132 Next → Page 30 of 49 · 971 questions