🌱 Spring Boot MCQ Questions – Page 20

Questions 381–400 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q381 medium code output
Given the following Spring Boot controller and model, what will be the output (the value of 'message' attribute in the Model) after a form submission with data 'name=Alice&email=alice@example.com'?
java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

// Assume User class exists with String name, String email and their getters/setters
// public class User { private String name; private String email; /*getters/setters*/ }

@Controller
public class UserController {
    @PostMapping("/register")
    public String registerUser(@ModelAttribute User user, Model model) {
        model.addAttribute("message", "User registered: " + user.getName());
        return "success";
    }
}
Q382 medium code output
A user "testuser" successfully logs in. Subsequently, another attempt is made to log in as "testuser" from a different browser or machine. What is the typical outcome of this second login attempt?
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.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())
            .sessionManagement(session -> session
                .maximumSessions(1)
                .maxSessionsPreventsLogin(true) // Prevent new logins when session limit reached
            )
            .csrf(csrf -> csrf.disable());
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withUsername("testuser").password("{noop}password").roles("USER").build();
        return new InMemoryUserDetailsManager(user);
    }
}
Q383 medium code error
If a client sends a `UserDto` with `username=""` (an empty string) to this POST endpoint, what will be the most likely outcome regarding validation?
java
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {
    @PostMapping
    public String createUser(@RequestBody UserDto user) {
        return "User created: " + user.getUsername();
    }
}

class UserDto {
    @NotNull @Size(min = 3, max = 20)
    private String username;
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
}
Q384 medium code error
Examine the following code snippet. What error will you encounter during compilation?
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("/status-error")
    public ResponseEntity<String> getStatusError() {
        return ResponseEntity.status("OK").body("Status text as string").build();
    }
}
Q385 medium code error
What error will occur when accessing `/api/list?ids=1,two,3` with the following Spring Boot controller?
java
import org.springframework.web.bind.annotation.*;
import java.util.List;

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

    @GetMapping("/list")
    public String getList(@RequestParam List<Integer> ids) {
        return "IDs: " + ids.size();
    }
}
Q386 medium code output
What is the HTTP response body when a GET request is made to '/config' without any query parameters?
java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConfigController {
    @GetMapping("/config")
    public String getConfig(@RequestParam(required = false, defaultValue = "default_config") String type) {
        return "Configuration type: " + type;
    }
}
Q387 medium
Which of the following events occurs after a bean's properties have been populated and aware interfaces have been processed, but before any of the standard initialization callbacks (like @PostConstruct or afterPropertiesSet()) are invoked?
Q388 medium code error
What happens when Spring Boot tries to initialize MyService?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
class MyService {
    @Autowired
    private int myIntProperty;
}
Q389 medium code error
A `BookingForm` has a `private LocalDate bookingDate;` field. An HTML form input is `<input type="text" name="bookingDate" value="2023-10-26">`. What error will occur during form submission if no `Converter` or `Formatter` is explicitly registered for `LocalDate`?
java
import java.time.LocalDate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ModelAttribute;

public class BookingForm {
    private LocalDate bookingDate;
    // Getters and Setters, default constructor...
}

@Controller
public class BookingController {
    @PostMapping("/book")
    public String submitBooking(@ModelAttribute BookingForm bookingForm) {
        return "bookingConfirmation";
    }
}
Q390 medium code output
What is the output of this code snippet, assuming the database contains products: (id=1, name='Chair', price=150.0), (id=2, name='Table', price=300.0), (id=3, name='Lamp', price=80.0), (id=4, name='Sofa', price=500.0)?
java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;

interface ProductRepository extends JpaRepository<Product, Long> {
    @Query(value = "SELECT name FROM product WHERE price > ?1 ORDER BY name DESC", nativeQuery = true)
    List<String> findProductNamesExpensiveNative(double minPrice);
}

// Assuming Product and ProductRepository are properly defined and wired
// and 'productRepository' is an injected instance.

public class TestService {
    ProductRepository productRepository;

    public TestService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    public List<String> getExpensiveProductNames(double threshold) {
        return productRepository.findProductNamesExpensiveNative(threshold);
    }
}
// In a conceptual main method or test:
// System.out.println(new TestService(productRepositoryMock).getExpensiveProductNames(100.0));
Q391 medium
When designing a REST API, when would it be more appropriate to return a plain object annotated with `@ResponseBody` instead of `ResponseEntity`?
Q392 medium code output
If the Spring Boot application above is packaged as `myapp.jar` and executed as `java -jar myapp.jar`, what will be printed to the console from the `CommandLineRunner`'s logger statements, given the default Spring Boot logging configuration (level INFO)?
java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SpringBootApplication
public class MyApplication {

    private static final Logger logger = LoggerFactory.getLogger(MyApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

    @Bean
    public CommandLineRunner runner() {
        return args -> {
            logger.trace("This is a TRACE message.");
            logger.debug("This is a DEBUG message.");
            logger.info("This is an INFO message.");
            logger.warn("This is a WARN message.");
            logger.error("This is an ERROR message.");
        };
    }
}
Q393 medium code output
What is the output of this code?
java
package com.example;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

class MyManualRepository { // No @Repository annotation
    public MyManualRepository() {
        System.out.println("MyManualRepository instance created.");
    }
    public String fetchData() {
        return "Data from manual repo.";
    }
}

@Configuration
class AppConfig {
    @Bean
    public MyManualRepository myManualRepository() {
        return new MyManualRepository();
    }
}

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
        MyManualRepository repo = context.getBean(MyManualRepository.class);
        System.out.println(repo.fetchData());
        context.close();
    }
}
Q394 medium code error
A Spring Boot application uses the following controller and `UserForm` with validation annotations. If the `spring-boot-starter-validation` dependency is missing from `pom.xml`, what error will occur when a form is submitted to `/register`?
java
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

public class UserForm {
    @NotNull @Email String email;
    // Getters and Setters...
}

@Controller
public class RegistrationController {
    @PostMapping("/register")
    public String registerUser(@Valid @ModelAttribute UserForm userForm, BindingResult result) {
        return "userRegistered";
    }
}
Q395 medium code output
Assuming `application.properties` contains `app.message=Welcome to Spring!`, what will this code print?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;

@Component class MessageComponent {
    @Value("${app.message:Default Message}")
    private String message;
    public String getMessage() { return message; }
}

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        var context = SpringApplication.run(DemoApplication.class, args);
        var component = context.getBean(MessageComponent.class);
        System.out.println(component.getMessage());
    }
}
Q396 medium code error
Given the following Spring Boot controller and form-backing object, what error will occur when Spring tries to bind form data to an instance of `ProductForm` on submission?
java
public class ProductForm {
    private String name;
    private double price;

    public ProductForm(String name, double price) {
        this.name = name;
        this.price = price;
    }
    // Getters and Setters...
}

@Controller
public class ProductController {
    @PostMapping("/products")
    public String addProduct(@ModelAttribute ProductForm productForm) {
        return "success";
    }
}
Q397 medium code error
Consider a custom class `MyCustomSetting` and a Spring component that attempts to inject a property into it. What error will occur during application startup?
java
java
public class MyCustomSetting {
    private String value;

    // Assume no constructor or setter that takes a single String
    public MyCustomSetting() {}
    public String getValue() { return value; }
    public void setValue(String value) { this.value = value; }
}

@Component
public class ConfigProcessor {
    @Value("${app.custom.setting}")
    private MyCustomSetting setting;

    public MyCustomSetting getSetting() {
        return setting;
    }
}


properties
# application.properties
app.custom.setting=someStringValue
Q398 medium
What happens if a `@RequestParam` or `@PathVariable` annotated parameter is marked as `required = false` and the corresponding parameter is missing in the request?
Q399 medium
What is the correct order of execution for destruction callbacks in a Spring bean?
Q400 medium
When defining `@RequestMapping` on a method, if no `path` or `value` attribute is specified, what is the default behavior?
← Prev 1819202122 Next → Page 20 of 49 · 971 questions