🌱 Spring Boot MCQ Questions – Page 24

Questions 461–480 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q461 medium code output
What is the output of this code when the `main` method of `MainRunner` is executed?
java
// src/main/java/com/example/demo/MainRunner.java
package com.example.demo;

import org.springframework.boot.SpringApplication;

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

// src/main/java/com/example/demo/AppConfig.java
package com.example.demo;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@SpringBootApplication
class AppConfig {
    // This class is intended as the primary Spring Boot configuration
}

// src/main/java/com/example/demo/MyComponent.java
package com.example.demo;

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

@Component
class MyComponent {
    @PostConstruct
    public void init() {
        System.out.println("MyComponent Initialized");
    }
}
Q462 medium code output
Given the Spring Boot controller below, what is the outcome regarding the view and model attributes if a request is made to `/products`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.ui.Model;

@Controller
public class ProductController {

    @ModelAttribute("categories")
    public String[] addCategories() {
        return new String[]{"Electronics", "Books"};
    }

    @GetMapping("/products")
    public String showProducts(Model model) {
        model.addAttribute("title", "All Products");
        return "productList";
    }
}
Q463 medium code output
Assuming this Spring Boot application is packaged as a JAR and executed with `java -jar myapp.jar`, what will be one of the last lines printed to the console during a successful startup?
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;

@SpringBootApplication
public class MyApplication {

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

    @Bean
    public CommandLineRunner run() {
        return args -> {
            System.out.println("Application has started successfully!");
        };
    }
}
Q464 medium code error
What error will occur during the startup of this Spring Boot application?
java
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("unknownScopeName") // This scope name is not defined in Spring
public class MyScopedComponent {
    public String message() {
        return "Hello from scoped component!";
    }
}
Q465 medium code output
What is the output of this code?
java
package com.example;

import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@Repository
class SimpleDataRepository {
    public String retrieveData() {
        return "Data fetched successfully from repo.";
    }
}

@Service
class DataDisplayService {
    @Autowired SimpleDataRepository repo;
    public void displayData() {
        System.out.println(repo.retrieveData());
    }
}

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
        DataDisplayService service = context.getBean(DataDisplayService.class);
        service.displayData();
        context.close();
    }
}
Q466 medium
What is the default scope for beans managed by the `ApplicationContext` in a Spring Boot application?
Q467 medium code output
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": "invalid-email-format", "age": 25 }`
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
}
Q468 medium code error
What error will occur when Spring attempts to instantiate `RestrictedComponent`?
java
import org.springframework.stereotype.Component;

@Component
public class RestrictedComponent {
    private RestrictedComponent() {
        // Initialization logic
    }
}
Q469 medium code error
Consider the following Spring Boot controller. If `dashboard.html` attempts to display `${data.value}` where `data` is the attribute set in the controller, what is the outcome?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;

@Controller
public class DashboardController {

    @GetMapping("/dashboard")
    public String showDashboard(Model model) {
        model.addAttribute("myData", "Some string value");
        return "dashboard"; // Assumes dashboard.html tries to access ${data.value}
    }
}
Q470 medium code error
What error will occur when the ApplicationContext tries to instantiate 'MyService' due to an unresolvable constructor dependency?
java
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

class ExternalDependency { // Not a Spring component
    public ExternalDependency() {}
}

@Component
class MyService {
    public MyService(ExternalDependency dependency) {
        // Constructor injection
    }
}

public class MissingDependencyApp {
    public static void main(String[] args) {
        new AnnotationConfigApplicationContext(MissingDependencyApp.class.getPackage().getName());
    }
}
Q471 medium code output
Given a `Movie` entity with a custom sequence generator, what will be the IDs of the first two saved movies?
java
import jakarta.persistence.*;

@Entity
@SequenceGenerator(name = "movie_seq", sequenceName = "MOVIE_SEQ", initialValue = 50, allocationSize = 1)
public class Movie {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "movie_seq")
    private Long id;
    private String title;

    public Movie() {}
    public Movie(String title) { this.title = title; }
    public Long getId() { return id; }
}

// Assume movieRepository is injected and available
// Assume transaction context is active
Movie movie1 = new Movie("Inception");
movieRepository.save(movie1);
Movie movie2 = new Movie("Dunkirk");
movieRepository.save(movie2);
System.out.println("Movie 1 ID: " + movie1.getId() + ", Movie 2 ID: " + movie2.getId());
Q472 medium code error
A client attempts to delete an item via `DELETE /api/items/123`. What will be the outcome with this code snippet?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMethod;

@RestController
@RequestMapping("/api/items")
public class ItemController {

    private ItemService itemService; // Assume injected

    @RequestMapping(value = "/{itemId}", method = RequestMethod.GET)
    public ResponseEntity<Void> deleteItem(@PathVariable String itemId) {
        itemService.deleteItem(itemId);
        return ResponseEntity.noContent().build();
    }
}
Q473 medium code output
What is the HTTP response status code when accessing `/item?id=123` with the following controller, assuming `name` is required by default?
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 ItemController {

    @GetMapping("/item")
    @ResponseBody
    public String getItemDetails(
            @RequestParam long id,
            @RequestParam String name) {
        return "Item: " + name + " (" + id + ")";
    }
}
Q474 medium code output
What is the output of this code?
java
package com.example;

import org.springframework.stereotype.Repository;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@Repository("primaryProductRepo")
class PrimaryProductRepository {
    public String getProductName() {
        return "Primary Product";
    }
}

@Repository
class SecondaryProductRepository {
    public String getProductName() {
        return "Secondary Product";
    }
}

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
        PrimaryProductRepository primaryRepo = (PrimaryProductRepository) context.getBean("primaryProductRepo");
        System.out.println(primaryRepo.getProductName());
        context.close();
    }
}
Q475 medium code output
A user named "user" with role "USER" attempts to access the `/api/user/data` endpoint after logging in. What is the expected HTTP status code and response body?
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 org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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
                .requestMatchers("/api/public/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            ).formLogin(withDefaults()).csrf(csrf -> csrf.disable());
        return http.build();
    }
    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withUsername("user").password("{noop}password").roles("USER").build();
        return new InMemoryUserDetailsManager(user);
    }
}

@RestController
public class MyController {
    @GetMapping("/api/public/data") public String getPublicData() { return "Public data"; }
    @GetMapping("/api/admin/data") public String getAdminData() { return "Admin data"; }
    @GetMapping("/api/user/data") public String getUserData() { return "User data"; }
}
Q476 medium code error
A Spring Boot controller has a handler method to process form submissions. If an HTML form is configured to submit with `method="post"` to `/submitData`, but the controller method is defined as shown, what error will the client receive?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;

public class DataForm {
    private String value;
    // Getters and Setters, default constructor...
}

@Controller
public class DataController {
    @GetMapping("/submitData")
    public String processData(@ModelAttribute DataForm dataForm) {
        return "dataSuccess";
    }
}
Q477 medium code output
What does this code print to the console when run as a Spring Boot application?
java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@Component @Lazy
class LazyService { 
    public LazyService() { System.out.println("LazyService initialized."); }
    public void doWork() { System.out.println("LazyService working."); }
}

@Component
class EagerClient implements CommandLineRunner {
    @Autowired
    private LazyService lazyService;
    public EagerClient() { System.out.println("EagerClient created."); }
    @Override
    public void run(String... args) {
        // lazyService is not explicitly used here.
        System.out.println("EagerClient run method completed.");
    }
}

@SpringBootApplication
public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
Q478 medium code output
Consider a Spring Boot application annotated with `@EnableEurekaClient`. If its `application.yml` only contains the application name and server port (without explicit Eureka client configuration), which `defaultZone` URL will it attempt to connect to?
yaml
spring:
  application:
    name: user-service

server:
  port: 8083
Q479 medium code output
What is the output of this code?
java
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

interface MyBean { String getName(); }
@Component("beanA") class BeanA implements MyBean { public String getName() { return "A"; } }
@Component("beanB") class BeanB implements MyBean { public String getName() { return "B"; } }

@SpringBootApplication
public class App7 {
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(App7.class, args);
        MyBean bean = (MyBean) ctx.getBean("beanB");
        System.out.println(bean.getName());
    }
}
Q480 medium code error
A client calls `DELETE /api/items/{id}` for an `id` that does NOT exist in the database. What will be the outcome of the `itemRepository.deleteById(id)` call in the service layer?
java
import org.springframework.stereotype.Service;
import org.springframework.data.jpa.repository.JpaRepository;

interface ItemRepository extends JpaRepository<Item, Long> {}

@Service
public class ItemService {

    private ItemRepository itemRepository; // Assume injected

    public void deleteItem(Long id) {
        itemRepository.deleteById(id);
        // No explicit check for existence or exception handling if not found
    }
}
// Assume Item class exists
← Prev 2223242526 Next → Page 24 of 49 · 971 questions