🌱 Spring Boot MCQ Questions – Page 39

Questions 761–780 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q761 medium code output
What is the result of running this Spring Boot application?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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.NoSuchBeanDefinitionException;

interface MyService { String execute(); }

@Component("primaryService")
class PrimaryServiceImpl implements MyService { @Override public String execute() { return "Executing Primary Service"; } }

@Component
class ErrorRunner implements CommandLineRunner {
    @Autowired
    @Qualifier("nonExistentService")
    private MyService myService;

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

@SpringBootApplication
class App {}
Q762 medium code output
What will be the value of `user.getName()` after the `profileUpdate` method is called with a POST request to '/profile/update' containing form data 'fullName=Evan&email=evan@example.com'?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ModelAttribute;

// User.java
public class User {
    private String name; private String email;
    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 ProfileController {
    @PostMapping("/profile/update")
    public String profileUpdate(@ModelAttribute User user) {
        // user object is processed here
        return "profile_view";
    }
}
Q763 medium code error
A client sends a POST request to `/api/users` with a JSON body: `{"name":"John Doe"}`. What error will occur when this controller method processes the request?
java
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class UserController {
    @PostMapping("/users")
    public String createUser(User user) {
        // Imagine User is a simple POJO with name field
        return "User created: " + user.getName();
    }
}
class User {
    private String name;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public User() {}
}
Q764 medium code output
Given a `MyService` with a method `process(String input)` that throws `IllegalArgumentException` if `input` is null or empty (message: "Input cannot be empty."), what is the output of this test code?
java
import com.example.demo.service.MyService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.assertThrows;

@SpringBootTest
class MyServiceExceptionTest {
    @Autowired
    MyService myService;

    @Test
    void testProcessThrowsException() {
        IllegalArgumentException thrown = assertThrows(
            IllegalArgumentException.class,
            () -> myService.process(null),
            "Expected process() to throw IllegalArgumentException, but it didn't"
        );
        System.out.print(thrown.getMessage());
    }
}
Q765 medium code error
What error will occur when accessing `/api/greet` with the following Spring Boot controller?
java
import org.springframework.web.bind.annotation.*;

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

    @GetMapping("/greet")
    public String greetUser(@RequestParam String name) {
        return "Hello, " + name + "!";
    }
}
Q766 medium code error
Consider the scenario where a bean is expected to be of a certain type, but the ApplicationContext provides an incompatible type. What error would occur?
java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;

@Configuration
class AppConfig {
    @Bean("numberBean")
    public Integer createNumber() {
        return 123;
    }
}

public class TypeMismatchApp {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        context.getBean("numberBean", String.class);
    }
}
Q767 medium
A Spring component needs direct programmatic access to the `ApplicationContext` it runs within. Which Spring interface should this component implement to achieve this?
Q768 medium
Which type of dependency injection is generally recommended for immutable dependencies and has been the default preference in Spring Boot versions 2.3 and later when a single constructor is present?
Q769 medium code output
What is the output of this code?
java
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Collections;
import java.util.List;

public class SecureService {
    @PreAuthorize("!isAnonymous()")
    public String getSensitiveData() { return "Sensitive Data"; }
}

public class TestRunner {
    public static void main(String[] args) {
        SecurityContextHolder.getContext().setAuthentication(
            new AnonymousAuthenticationToken("key", "anonymousUser", Collections.singletonList(new SimpleGrantedAuthority("ROLE_ANONYMOUS")))
        );
        SecureService service = new SecureService();
        try { System.out.println(service.getSensitiveData()); }
        catch (Exception e) { System.out.println(e.getClass().getSimpleName()); }
    }
}
Q770 medium
Why is it generally considered good practice to use `@Service` instead of just `@Component` for business logic classes?
Q771 medium
What is a key semantic difference between using `@Service` and `@Repository`?
Q772 medium code output
Given the Feign Client setup and a dynamic URL through `application.properties`, what URL will Feign attempt to call?
java
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

// application.properties: my.service.baseurl=http://api.example.com/v1

@FeignClient(name = "dynamicService", url = "${my.service.baseurl}/products")
interface DynamicServiceClient {
    @GetMapping("/{productId}")
    String getProduct(@PathVariable("productId") String id);
}

public class TestApplication {
    public static void main(String[] args) {
        // In a real Spring Boot app, PropertyResolver would resolve 'my.service.baseurl'.
        // For this snippet, assume it resolves to 'http://api.example.com/v1'.
        String resolvedUrlBase = "http://api.example.com/v1";
        String feignClientUrl = resolvedUrlBase + "/products"; // As constructed by Feign
        String finalUrl = feignClientUrl + "/" + "P123"; // Path variable added
        System.out.println(finalUrl);
    }
}
Q773 medium code output
What does this code print to the console?
java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;

@SpringBootTest
class SimpleSpringBootTest {
    @Autowired
    ApplicationContext context;

    @Test
    void contextLoads() {
        System.out.print("Context loaded successfully!");
    }
}
Q774 medium code output
What is the output of this code when a GET request is made to '/report' with an 'Accept: text/html' header?
java
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ReportController {
    @RequestMapping(value = "/report", produces = "application/json")
    public String getJsonReport() {
        return "{\"report\": \"data\"}";
    }

    @RequestMapping(value = "/report", produces = "text/plain")
    public String getTextReport() {
        return "Report data in text format.";
    }
}
Q775 medium code output
Assume `DevComponent` is a `@Component` with `@Profile("dev")` and `ProdComponent` is a `@Component` with `@Profile("prod")`, each returning a distinct message. What does this code print to the console when `testActiveProfile` is executed?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.junit.jupiter.api.Test;

// DevComponent (returns 'Hello from Dev Profile') and ProdComponent (returns 'Hello from Prod Profile') (not shown)
@SpringBootTest
@ActiveProfiles("dev")
public class ActiveProfilesTest {

    @Autowired(required = false)
    private DevComponent devComponent;

    @Autowired(required = false)
    private ProdComponent prodComponent;

    @Test
    void testActiveProfile() {
        if (devComponent != null) {
            System.out.println(devComponent.getProfileMessage());
        } else if (prodComponent != null) {
            System.out.println(prodComponent.getProfileMessage());
        } else {
            System.out.println("No component loaded for active profile.");
        }
    }
}
Q776 medium code output
Consider the following Spring Boot application. What will be printed to the console?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

interface ComponentService { String getName(); }

@Component("serviceA")
class ServiceA implements ComponentService { @Override public String getName() { return "ServiceA"; } }

@Component("serviceB")
class ServiceB implements ComponentService { @Override public String getName() { return "ServiceB"; } }

@Configuration
class MyConfig {
    @Bean
    public String combinedName(@Qualifier("serviceA") ComponentService s1, @Qualifier("serviceB") ComponentService s2) {
        return "Combined: " + s1.getName() + " and " + s2.getName();
    }
}

@Component
class CombinedRunner implements CommandLineRunner {
    @Autowired
    private String combinedName;

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

@SpringBootApplication
class App {}
Q777 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": "alice@example.com", "age": null }`
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
}
Q778 medium code output
What is the output of this Spring Boot application?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(MyApp.class, args);
        UserService userService = context.getBean(UserService.class);
        System.out.println(userService.getUserData());
    }
}

class DataSource {
    public String getConnection() { return "Database connection established"; }
}

class UserService {
    private DataSource dataSource;
    public UserService(DataSource dataSource) { this.dataSource = dataSource; }
    public String getUserData() { return "Fetching user data: " + dataSource.getConnection(); }
}

@Configuration
class AppConfig {
    @Bean
    public DataSource myDataSource() { return new DataSource(); }

    @Bean
    public UserService myUserService(DataSource dataSource) { // Spring injects DataSource
        return new UserService(dataSource);
    }
}
Q779 medium code output
Given a `MyService` with a `greet()` method that returns "Hello from MyService!", what is the output of this test code?
java
import com.example.demo.service.MyService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.SpyBean;
import static org.mockito.Mockito.when;

@SpringBootTest
class MyServiceSpyTest {
    @SpyBean
    MyService myService;

    @Test
    void testSpiedService() {
        System.out.println(myService.greet());
        when(myService.greet()).thenReturn("Spied Hello!");
        System.out.print(myService.greet());
    }
}
Q780 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;

// Simulate a Hibernate exception class
class ConstraintViolationException extends org.hibernate.exception.ConstraintViolationException {
    public ConstraintViolationException(String message, Throwable cause, String constraintName) {
        super(message, cause, constraintName);
    }
}

@Repository
class ProductRepository {
    public void save(String name) {
        throw new ConstraintViolationException("Duplicate key error", null, "uk_product_name");
    }
}

@Service
class ProductService {
    @Autowired ProductRepository repo;
    public void addProduct(String name) {
        try {
            repo.save(name);
        } catch (Exception e) {
            System.out.println("Caught exception in service: " + e.getClass().getSimpleName());
        }
    }
}

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
        ProductService service = context.getBean(ProductService.class);
        service.addProduct("test");
        context.close();
    }
}
← Prev 3738394041 Next → Page 39 of 49 · 971 questions