🌱 Spring Boot MCQ Questions – Page 43

Questions 841–860 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q841 medium code output
What is the output of this code when a GET request is made to '/admin/users/details'?
java
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AdminController {
    @RequestMapping("/admin/**")
    public String handleAdminWildcard() {
        return "Accessed admin area with wildcard.";
    }

    @RequestMapping("/admin/users/{id}")
    public String handleSpecificUser() {
        return "Accessed specific user in admin.";
    }
}
Q842 medium
If you try to use `@RequestBody` on a controller method parameter of type `String` with a `Content-Type` of `text/plain`, what is the expected outcome?
Q843 medium
To return a custom HTTP status code, a custom response body, and potentially custom headers (like a 'Location' header after a POST) from a Spring Boot controller method, which return type is most flexible and recommended?
Q844 medium code output
Considering the controller and User model below, what will be the value of `result.hasErrors()` if a form is submitted with 'name=&email=invalid'?
java
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Email;

// User.java
public class User {
    @NotEmpty private String name;
    @Email private String email;
    public User() {} // important for binding
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}

@Controller
public class ValidationController {
    @PostMapping("/validate")
    public String validateUser(@Valid @ModelAttribute User user, BindingResult result) {
        if (result.hasErrors()) {
            return "form";
        }
        return "success";
    }
}
Q845 medium code output
Assume there is a `MyApplicationRunner` class that is a `@Component` and implements `ApplicationRunner`, printing "ApplicationRunner executed!" in its `run` method. What is the complete output of this code when `contextLoadsAndApplicationRunnerRuns` is executed?
java
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.jupiter.api.Test;

// MyApplicationRunner (not shown) is an @Component that implements ApplicationRunner
// and prints "ApplicationRunner executed!" in its run method.
@SpringBootTest
public class ApplicationRunnerTest {

    @Test
    void contextLoadsAndApplicationRunnerRuns() {
        System.out.println("Test method finished.");
    }
}
Q846 medium
When designing a Spring Boot component, which form of dependency injection is generally recommended for mandatory dependencies, promoting immutability and easier testing?
Q847 medium
If a `@Controller` method encounters an unhandled exception during processing, what is the typical default behavior in a Spring Boot application if no specific `@ExceptionHandler` is defined?
Q848 medium code error
What error will occur when Spring tries to create a bean from `MySingletonEnum`?
java
import org.springframework.stereotype.Component;

@Component
public enum MySingletonEnum {
    INSTANCE;

    public void doWork() {
        System.out.println("Doing work in enum instance.");
    }
}
Q849 medium code output
Given the Spring Boot controller above, what will be the HTTP response body when a GET request is made to `/api/info` with an `Accept: application/json` header?
java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.MediaType;

@RestController
public class InfoController {
    @GetMapping(value = "/api/info", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getInfo() {
        return "{\"name\": \"AppService\", \"version\": \"1.0\"}";
    }
}
Q850 medium code output
Given a `MyComponent` that injects `app.message` property via `@Value("${app.message:Default Message}")`, what does this test code print?
java
import com.example.demo.component.MyComponent;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;

@SpringBootTest
@TestPropertySource(properties = {"app.message=Test Specific Message"})
class TestPropertySourceTest {
    @Autowired
    MyComponent myComponent;

    @Test
    void testPropertyValue() {
        System.out.print(myComponent.getMessage());
    }
}
Q851 medium code output
What is the expected output of this Spring Boot application?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;

interface Repository { String fetchData(); }

@Component
class JpaRepositoryImpl implements Repository { @Override public String fetchData() { return "Data from JPA"; } }

@Component
class JdbcRepositoryImpl implements Repository { @Override public String fetchData() { return "Data from JDBC"; } }

@Component
class DataAccessRunner implements CommandLineRunner {
    @Autowired
    private Repository repository;

    @Override
    public void run(String... args) { System.out.println(repository.fetchData()); }
}

@SpringBootApplication
class App {}
Q852 medium code output
What is the HTTP response body when a GET request is made to '/search?query=SpringBoot'?
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 SearchController {
    @GetMapping("/search")
    public String search(@RequestParam String query) {
        return "Searching for: " + query;
    }
}
Q853 medium code output
What is the output of this code snippet, assuming the database contains products: (id=1, name='Keyboard', price=75.0), (id=2, name='Mouse', price=50.0), (id=3, name='Monitor', price=200.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("SELECT p.name FROM Product p WHERE p.price > ?1 ORDER BY p.name")
    List<String> findProductNamesPricierThan(double price);
}

// 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> getNames(double minPrice) {
        return productRepository.findProductNamesPricierThan(minPrice);
    }
}
// In a conceptual main method or test:
// System.out.println(new TestService(productRepositoryMock).getNames(60.0));
Q854 medium
Which attribute of `@RequestMapping` is used to specify that a handler method should only process requests with a specific HTTP method, such as GET?
Q855 medium code output
What is the output of this code when the `main` method of `MyApplication` is executed? (Assume default logging is suppressed, focus on `System.out`)
java
// src/main/java/com/example/myapp/MyApplication.java
package com.example.myapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.CommandLineRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class MyApplication {
    @Autowired(required = false)
    private SubPackageService subPackageService;

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

    @Bean
    public CommandLineRunner run() {
        return args -> {
            if (subPackageService != null) {
                System.out.println("SubPackageService found.");
            } else {
                System.out.println("SubPackageService not found.");
            }
        };
    }
}

// src/main/java/com/example/myapp/sub/SubPackageService.java
package com.example.myapp.sub;

import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;

@Service
public class SubPackageService {
    @PostConstruct
    public void init() {
        System.out.println("SubPackageService Initialized from subpackage");
    }
}
Q856 medium code output
What output does the `MyApplication` produce?
java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.CommandLineRunner;

@Component
class ConfigService {
    public String getConfigValue() { return "App Config Value"; }
}

@Component
class MethodInjectedBean {
    private String value;

    @Autowired
    public void initialize(ConfigService service) { // Method injection
        this.value = "Initialized with: " + service.getConfigValue();
    }

    public String getValue() { return value; }
}

@Component
class MyRunner implements CommandLineRunner {
    @Autowired
    private MethodInjectedBean bean;

    @Override
    public void run(String... args) {
        System.out.println(bean.getValue());
    }
}

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
Q857 medium code output
Assuming `src/main/resources/application.properties` contains `app.env.greeting=Hello from application.properties`, and `EnvironmentService` injects `@Value("${app.env.greeting}")`. What does this code print to the console when `testApplicationPropertiesLoading` is executed?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.jupiter.api.Test;

// EnvironmentService (not shown) injects @Value("${app.env.greeting}")
// application.properties (not shown) contains: app.env.greeting=Hello from application.properties
@SpringBootTest
public class PropertyLoadingTest {

    @Autowired
    private EnvironmentService environmentService;

    @Test
    void testApplicationPropertiesLoading() {
        System.out.println(environmentService.getGreeting());
    }
}
Q858 medium code output
What happens when a new `Author` is saved along with a new `Book` through a `@ManyToOne` relationship from `Book` to `Author`, but `CascadeType.ALL` is not used for `Author`?
java
import jakarta.persistence.*;

@Entity
public class Author {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
    private String name;
    public Author() {} public Author(String name) { this.name = name; } public Long getId() { return id; }
}

@Entity
public class Book {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
    private String title;
    @ManyToOne
    @JoinColumn(name = "author_id")
    private Author author;
    public Book() {} public Book(String title, Author author) { this.title = title; this.author = author; } public Long getId() { return id; }
}

// Assume bookRepository and authorRepository are injected
// Assume transaction context is active
Author newAuthor = new Author("J.K. Rowling");
Book newBook = new Book("Harry Potter", newAuthor);
bookRepository.save(newBook);

System.out.println("Book ID: " + newBook.getId());
System.out.println("Author ID: " + newAuthor.getId());
System.out.println("Author in DB? " + (authorRepository.findById(newAuthor.getId()).isPresent() ? "Yes" : "No"));
Q859 medium
How can a `@Controller` method programmatically redirect the client's browser to a different URL (e.g., `/dashboard`) after processing a request?
Q860 medium code error
What error will be encountered when making a POST request to `/api/submit` with a JSON body `{"data": "someValue"}` to the following controller?
java
import org.springframework.web.bind.annotation.*;

@RestController
public class MyController {
    @PostMapping("/api/submit")
    public String submitForm(@RequestParam String data) { // Expects query param
        return "Data: " + data;
    }
}
← Prev 4142434445 Next → Page 43 of 49 · 971 questions