🌱 Spring Boot MCQ Questions – Page 11
Questions 201–220 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsIf you remove `@SpringBootApplication` and instead use `@Configuration`, `@EnableAutoConfiguration`, and `@ComponentScan` separately on the same class, what would be the functional difference in a typical Spring Boot application?
Given the controller, what exception will be thrown if a POST request is made to '/api/data' *without* including the 'value' parameter in the request body?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class DataController {
@PostMapping("/api/data")
public String handleData(@RequestParam(required = true) String value) {
System.out.println("Received: " + value);
return "handled";
}
}
Which of the following is the best way to handle an *optional* path variable in Spring Boot, meaning the segment might sometimes be absent from the URL?
What does this code print, assuming the remote service successfully processes the request and echoes the message?
java
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@FeignClient(name = "messageService", url = "http://localhost:8081")
interface MessageServiceClient {
@PostMapping("/messages")
String postMessage(@RequestBody String message);
}
public class TestApplication {
public static void main(String[] args) {
MessageServiceClient client = msg -> "Received: '" + msg + "'"; // Mock implementation
System.out.println(client.postMessage("Hello Feign"));
}
}
Consider the following Spring component. What error will prevent the application from starting?
java
java
@Component
public class SpelCalculator {
@Value("#{T(java.lang.System).currentTimeMillis() / (1000 * 60)}")
private long minutesSinceEpoch;
public long getMinutesSinceEpoch() {
return minutesSinceEpoch;
}
}
properties
# application.properties (no relevant properties)
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/api/v1/data")
@RequestMapping(method = RequestMethod.POST, value = "/api/v1/data")
public String getData() {
return "Data";
}
}
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 java.util.List;
@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("SELECT p.name, p.price FROM Product p ORDER BY p.name")
List<Object[]> findNameAndPriceProjectionJPQL();
}
// Assume ProductRepository is autowired as 'productRepository'
// And the database contains:
// Product(id=1, name='Mouse', price=25.00)
// Product(id=2, name='Keyboard', price=75.00)
List<Object[]> results = productRepository.findNameAndPriceProjectionJPQL();
System.out.println(results.get(0)[0] + ": " + results.get(1)[1]);
Given a `User` entity and `UserRepository` (JpaRepository), what does this test code print to the console?
java
import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
@DataJpaTest
class TransactionalRollbackTest {
@Autowired
private UserRepository userRepository;
@Test
void testTransactionalBehavior() {
System.out.println("Before save: " + userRepository.count());
userRepository.save(new User("Charlie"));
System.out.print("After save: " + userRepository.count());
}
}
Which component is primarily responsible for converting the HTTP request body (e.g., JSON) into a Java object when `@RequestBody` is used?
Given the following Dockerfile and assuming `my-springboot-app.jar` exists, what command will be executed when the Docker container starts?
dockerfile
FROM openjdk:17-jre-slim
WORKDIR /app
COPY target/my-springboot-app.jar app.jar
EXPOSE 8080
CMD ["java", "-jar", "app.jar"]
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
{
"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
}
Which of the following statements accurately describes a characteristic of RESTful APIs built with `@RestController` regarding state management?
What content will the MockMvc test assert to be in the response body?
java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(controllers = TestController.class)
class TestControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testDeleteEndpoint() throws Exception {
mockMvc.perform(delete("/api/items/5"))
.andExpect(status().isAccepted())
.andExpect(content().string("Item 5 deleted."));
}
}
// Assuming TestController has:
// @RestController
// class TestController {
// @DeleteMapping("/api/items/{id}")
// public ResponseEntity<String> deleteItem(@PathVariable Long id) {
// return ResponseEntity.accepted().body("Item " + id + " deleted.");
// }
// }
Consider a Spring Boot application where a `MyDao` class is annotated with `@Repository`. If the `PersistenceExceptionTranslationPostProcessor` bean is NOT defined in the application's configuration, and `saveData` throws a Hibernate `ConstraintViolationException`, what type of exception will propagate to the caller of `myService.performSave()`?
java
package com.example.dao;
import org.springframework.stereotype.Repository;
import org.hibernate.exception.ConstraintViolationException;
@Repository
public class MyDao {
public void saveData() {
// Simulate a raw persistence exception
throw new ConstraintViolationException("Duplicate entry", new Exception(), "unique_constraint");
}
}
package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.dao.MyDao;
@Service
public class MyService {
@Autowired
private MyDao myDao;
public void performSave() {
myDao.saveData();
}
}
// Assuming app config is missing @Bean PersistenceExceptionTranslationPostProcessor
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 name = :productName", nativeQuery = true)
Optional<Product> findByNameExactNative(@Param("productName") String name);
}
// Assume ProductRepository is autowired as 'productRepository'
// And the database contains:
// Product(id=1, name='Webcam', price=50.00)
// Product(id=2, name='Microphone', price=70.00)
// Assume 'product' is the correct table name.
Optional<Product> webcam = productRepository.findByNameExactNative("Webcam");
Optional<Product> speaker = productRepository.findByNameExactNative("Speaker");
System.out.println(webcam.isPresent() + ", " + speaker.isPresent());
Which of the following statements best describes the purpose of the `ModelAndView` object in Spring MVC?
What error occurs when accessing `/reports` with the following controller?
java
import org.springframework.web.bind.annotation.*;
@RestController
public class ReportController {
@GetMapping("/reports")
public String getReport(@PathVariable String reportId) {
return "Report ID: " + reportId;
}
}
When a bean is defined using `@Component` on a class named `MyComplexCalculator` without an explicit bean name, what is the default qualifier value that `@Qualifier` would use to refer to this bean?
Given the following Java code snippet using JJWT for token generation, what will be printed to the console?
java
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Date;
public class JwtGenerator {
public static void main(String[] args) {
Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
String jwt = Jwts.builder()
.setSubject("testUser")
.setIssuedAt(new Date(0L)) // Epoch time for consistency
.setExpiration(new Date(10000L)) // Expire in 10 seconds from epoch
.signWith(key)
.compact();
System.out.println(jwt.startsWith("eyJ"));
}
}
What is the HTTP status code and response body when a POST request is sent to `/auth/login` if `AuthenticationFailedException` is thrown, given the Spring Boot setup?
java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
class AuthenticationFailedException extends RuntimeException {
public AuthenticationFailedException(String message) { super(message); }
}
@RestController
class AuthController {
@PostMapping("/auth/login")
public String login() {
throw new AuthenticationFailedException("Invalid credentials");
}
}
@RestControllerAdvice
class AuthExceptionHandler {
@ExceptionHandler(AuthenticationFailedException.class)
public ResponseEntity<Map<String, String>> handleAuthFailed(AuthenticationFailedException ex) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(Map.of("error", ex.getMessage()));
}
}