🌱 Spring Boot MCQ Questions – Page 7

Questions 121–140 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q121 medium code error
If the `execute()` method of `Svc` is called, what is the most likely runtime error?
java
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@Component class Dep { public String getData() { return "Data"; } }

@Component 
class Comp {
    @Autowired private Dep dep; 
    public String doSomething() { return dep.getData(); }
}

@Service class Svc {
    public String execute() {
        Comp comp = new Comp(); 
        return comp.doSomething();
    }
}
Q122 medium
Consider a typical Spring Boot application. If the main class annotated with `@SpringBootApplication` is in the package `com.example.app`, and a new `@Service` class is created in `com.example.app.services`, will it be discovered by default?
Q123 medium
What is the correct order of execution for initialization callbacks in a Spring bean?
Q124 medium code output
What is the output when accessing '/greet'?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

@RestController
public class GreetingController {

    @GetMapping("/greet")
    public String greet() {
        throw new IllegalArgumentException("Invalid greeting parameter");
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public String handleIllegalArgument(IllegalArgumentException ex, WebRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return "Request Problem: " + ex.getMessage() + ". Agent: " + (userAgent != null ? userAgent : "N/A");
    }
}
Q125 medium code output
What does this code print to the console when `App` is executed?
java
import javax.annotation.PreDestroy;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Component;

@Component
class MyBean {
    public MyBean() { System.out.println("1. MyBean Ctor"); }
    @PreDestroy public void destroy() { System.out.println("2. MyBean @PreDestroy"); }
}
@ComponentScan
public class App {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);
        System.out.println("3. Context Initialized");
        context.close();
    }
}
Q126 medium code error
A client makes a GET request to `/api/items/123`. What is the primary error that will prevent this method from correctly binding the 'id' value?
java
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class ItemController {
    @GetMapping("/items/{itemId}")
    public String getItemDetails(@PathVariable String id) {
        return "Item ID: " + id;
    }
}
Q127 medium code output
Given the Spring Boot application and the two configuration files packaged inside `myapp.jar` as shown, what will be the output when the application is executed with `java -jar myapp.jar`?
java
package com.example.demo;

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

@SpringBootApplication
public class MyApplication {

    @Value("${greeting.message}")
    private String message;

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

    @Bean
    public CommandLineRunner runner() {
        return args -> {
            System.out.println("Greeting: " + message);
        };
    }
}
// Assume myapp.jar contains:
// src/main/resources/application.properties:
// greeting.message=Hello from Properties

// src/main/resources/application.yml:
// greeting:
//   message: Hello from YAML
Q128 medium
How does the `@RestController` annotation simplify the implementation of POST endpoints in Spring Boot?
Q129 medium code output
What is the output of this code snippet, assuming `userRepository` is a JpaRepository for a `User` entity with an auto-incrementing `id` and the database is initially empty?
java
public class UserService {
    private UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User createUser(String name, String email) {
        User newUser = new User(name, email);
        User savedUser = userRepository.save(newUser);
        return savedUser;
    }
}

// In a test context or main method:
UserService service = new UserService(userRepository);
User user = service.createUser("Alice", "alice@example.com");
System.out.println(user.getId() != null ? "User created with ID: " + user.getId() : "User creation failed");
Q130 medium code error
What error will occur when this Spring Boot application attempts to start and access `MyService`?
java
package com.example.main;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.stereotype.Service;

package com.example.services;

@Service
public class MyService {
    // Service implementation
}

// In com.example.main package
@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}
Q131 medium code error
When a client sends a GET request to `/api/download`, what error or unexpected behavior will occur from this controller method?
java
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/api")
public class FileController {
    @GetMapping("/download")
    public String downloadFile(HttpServletResponse response) throws IOException {
        response.getWriter().write("File content.");
        return "Download started.";
    }
}
Q132 medium code error
A client sends a DELETE request to `/api/widgets` with query parameters `?id=1&id=2`. What error will this code produce?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import java.util.List;

@RestController
@RequestMapping("/api/widgets")
public class WidgetController {

    private WidgetService widgetService; // Assume injected

    @DeleteMapping
    public ResponseEntity<Void> deleteWidgets(@RequestBody List<Long> ids) {
        widgetService.deleteWidgets(ids);
        return ResponseEntity.noContent().build();
    }
}
Q133 medium code output
What is the HTTP response body when a GET request is made to '/api/status'?
java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StatusController {
    @GetMapping("/api/status")
    public ResponseEntity<String> getServiceStatus() {
        return new ResponseEntity<>("Service is operational", HttpStatus.OK);
    }
}
Q134 medium code output
Assuming a Spring Boot application with Thymeleaf configured with default prefix "classpath:/templates/" and suffix ".html", what is the full path to the template file that Spring Boot will attempt to resolve if a request is made to `/docs`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class PathController {

    @GetMapping("/docs")
    public String showDocument() {
        return "documents/report";
    }
}
Q135 medium code output
Given the Spring Boot controller above, what will be the HTTP response body when a GET request is made to `/status`?
java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StatusController {
    @GetMapping("/status")
    public ResponseEntity<String> checkStatus() {
        return new ResponseEntity<>("Service is operational", HttpStatus.OK);
    }
}
Q136 medium
In a typical Spring Boot application, how is the `ApplicationContext` primarily bootstrapped and initialized?
Q137 medium code output
A JWT is generated with a custom 'roles' claim. What will be the output when this specific claim is retrieved?
java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Arrays;
import java.util.List;

public class RoleClaimExtractor {
    public static void main(String[] args) {
        Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        List<String> userRoles = Arrays.asList("USER", "MANAGER");
        String jwt = Jwts.builder()
                .setSubject("bob")
                .claim("roles", userRoles)
                .signWith(key)
                .compact();
        
        Claims claims = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jwt).getBody();
        System.out.println(claims.get("roles", List.class).get(0));
    }
}
Q138 medium
Which Thymeleaf attribute is typically used on an HTML input element (e.g., `<input type='text'>`) to bind it to a specific property of the form's model object declared by `th:object`?
Q139 medium code error
What error will occur when Spring Boot tries to deserialize a JSON payload into the `Item` object for this POST request, for example `{"name": "Book"}`?
java
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/items")
public class ItemController {
    @PostMapping
    public Item createItem(@RequestBody Item item) {
        System.out.println("Creating item: " + item.getName());
        return item;
    }
}

class Item {
    private String name;
    public Item(String name) {
        this.name = name;
    }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}
Q140 medium code output
What will be the HTTP status code and response body when a GET request is made to `/report/download` if an `IOException` occurs, based on the Spring Boot code?
java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.sql.SQLException;

@RestController
class ReportController {
    @GetMapping("/report/download")
    public String downloadReport() throws IOException {
        throw new IOException("Failed to read report file");
    }
}

@RestControllerAdvice
class ReportExceptionHandler {
    @ExceptionHandler({IOException.class, SQLException.class})
    public ResponseEntity<String> handleFileOrDbErrors(Exception ex) {
        return new ResponseEntity<>("Report Error: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
← Prev 56789 Next → Page 7 of 49 · 971 questions