🌱 Spring Boot MCQ Questions – Page 41
Questions 801–820 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsWhat is the primary purpose of the `@Autowired` annotation in Spring Boot applications?
If you have a `@RestController` that needs to process form-encoded data (e.g., `application/x-www-form-urlencoded`) submitted via a POST request, which annotation would you typically use on a method parameter to bind this data to a Java object?
What is the HTTP status code and response body for a PUT request to `/api/products/999` with the JSON body `{"name": "New Product X", "price": 50.0}`?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.Map;
// Assume Product class has Long id, String name, Double price, with getters/setters and a constructor.
@RestController
@RequestMapping("/api/products")
public class ProductController {
private Map<Long, Product> products = new HashMap<>();
public ProductController() {
products.put(1L, new Product(1L, "Product A", 10.0));
}
@PutMapping("/{id}")
public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product productDetails) {
if (!products.containsKey(id)) {
return ResponseEntity.notFound().build();
}
Product existingProduct = products.get(id);
existingProduct.setName(productDetails.getName());
existingProduct.setPrice(productDetails.getPrice());
products.put(id, existingProduct);
return ResponseEntity.ok(existingProduct);
}
}
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.DeleteMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@DeleteMapping("/delete")
public ResponseEntity<Void> deleteResource() {
return ResponseEntity.noContent().build();
}
}
A Spring Boot application has a controller method designed to update a user by ID. If an HTML form attempts to submit to this endpoint without including the `userId` in the URL, which error will occur?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
public class UserUpdateForm {
private String newEmail;
// Getters and Setters...
}
@Controller
public class UserController {
@PostMapping("/users/{userId}/update")
public String updateUser(@PathVariable Long userId, @ModelAttribute UserUpdateForm userForm) {
// Logic to update user...
return "userProfile";
}
}
What is the primary effect of configuring `eureka.client.initial-instance-info-replication-interval-seconds` to a higher value like 60 (instead of default 40) during a Eureka client's startup?
yaml
spring:
application:
name: order-service
server:
port: 8086
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
initial-instance-info-replication-interval-seconds: 60
What is the output of this code snippet, assuming `userRepository` is a JpaRepository, initially containing a `User` with `id=1`, `name="Charlie"`, `email="charlie@example.com"`?
java
public class UserService {
private UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User updateUserEmail(Long id, String newEmail) {
return userRepository.findById(id)
.map(user -> {
user.setEmail(newEmail);
return userRepository.save(user);
})
.orElse(null);
}
}
// In a test context or main method:
UserService service = new UserService(userRepository);
User updatedUser = service.updateUserEmail(1L, "charlie.new@example.com");
System.out.println(updatedUser != null ? updatedUser.getEmail() : "Update failed");
Where should static resources like CSS, JavaScript, and images typically be placed in a Spring Boot application so they can be served directly by the embedded web server?
What is the forwarded URI for a request to `/legacy/resource` if the gateway configuration contains this route?
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("legacy_route", r -> r.path("/legacy/{segment}")
.filters(f -> f.rewritePath("/legacy/(?<segment>.*)", "/old-service/${segment}"))
.uri("http://localhost:8086"))
.build();
}
}
What is the HTTP status and body returned by the `createProduct` method when a POST request is made to `/products` with the body `"Laptop"` (Content-Type: text/plain)?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@RestController
@RequestMapping("/products")
class ProductController {
@PostMapping
public ResponseEntity<String> createProduct(@RequestBody String productName) {
return new ResponseEntity<>("Product created: " + productName, HttpStatus.CREATED);
}
}
What is the expected JSON path value for '$.message' in the response after performing this MockMvc request?
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.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.springframework.http.MediaType;
@WebMvcTest(controllers = TestController.class)
class TestControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testPostJson() throws Exception {
mockMvc.perform(post("/api/create")
.contentType(MediaType.APPLICATION_JSON)
.content("{ \"id\": 1, \"name\": \"New Item\" }"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.message").value("Item New Item created with ID: 1"));
}
}
// Assuming TestController has:
// @RestController
// class TestController {
// @PostMapping("/api/create")
// public ResponseEntity<String> createItem(@RequestBody Item item) {
// return ResponseEntity.status(201).body("{ \"message\": \"Item " + item.name + " created with ID: " + item.id + "\"}");
// }
// }
// class Item { public long id; public String name; }
An attempt is made to log in with username "testuser" and password "wrongpassword". What will be the typical outcome?
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated())
.formLogin(withDefaults()).csrf(csrf -> csrf.disable());
return http.build();
}
@Bean
public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
UserDetails user = User.withUsername("testuser").password(passwordEncoder.encode("correctpassword")).roles("USER").build();
return new InMemoryUserDetailsManager(user);
}
@Bean
public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }
}
Which type of injection is generally recommended as best practice for mandatory dependencies when using `@Autowired` in Spring Boot?
What does this code print to the console when run as a Spring Boot application?
java
import org.springframework.stereotype.Component;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.annotation.PostConstruct;
@Component
class LifecycleBean implements CommandLineRunner {
public LifecycleBean() { System.out.println("LifecycleBean: Constructor called."); }
@PostConstruct
public void init() {
System.out.println("LifecycleBean: @PostConstruct called.");
}
@Override
public void run(String... args) {
System.out.println("LifecycleBean: CommandLineRunner run method called.");
}
}
@SpringBootApplication
public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
What does this code print to the console when `App` is executed?
java
import javax.annotation.PostConstruct;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Component;
@Component("myService") class MyService { public MyService() { System.out.println("1. MyService Ctor"); } @PostConstruct public void init() { System.out.println("2. MyService @PostConstruct"); } }
@Component class MyProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object b, String n) throws BeansException { return b; } @Override public Object postProcessAfterInitialization(Object b, String n) throws BeansException { if (b instanceof MyService) System.out.println("3. After Init: " + n); return b; } }
@ComponentScan
public class App { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class); context.close(); } }
What is one of the main advantages of using Inversion of Control (IoC) and Dependency Injection (DI) in Spring Boot applications?
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": "Alice",
"email": "alice@example.com"
}`
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
}
Assuming a Spring Boot application with the given controller, if a request is made to `/report` and no explicit view name is returned, what is the outcome regarding the view name and model attributes?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.HashMap;
import java.util.Map;
@Controller
public class MapDataController {
@GetMapping("/report")
public Map<String, Object> generateReport() {
Map<String, Object> modelData = new HashMap<>();
modelData.put("reportName", "Monthly Sales");
modelData.put("totalSales", 50000.00);
return modelData;
}
}
You need to return an HTTP 400 Bad Request status with a custom `ErrorResponse` object in the body. Which `ResponseEntity` builder method is best suited for this?
Which of the following correctly creates a `ResponseEntity` representing an HTTP 204 No Content status?