🌱 Spring Boot MCQ Questions – Page 33

Questions 641–660 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q641 medium code error
Given the following Spring Boot setup, what error will you encounter during application startup?
java
package com.example.app;

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

interface DataProvider {
    String provideData();
}

@Service
class ConcreteDataProvider implements DataProvider {
    @Override
    public String provideData() {
        return "Concrete Data";
    }
}

@Service
class DataProcessor {
    private final DataProvider dataProvider;

    @Autowired
    public DataProcessor(DataProvider dataProvider) {
        this.dataProvider = dataProvider;
    }
}

// Imagine a main SpringBootApplication class exists and scans this package.
Q642 medium code output
Considering the Spring Boot application, if it's packaged as `myapp.jar` and executed, what will be a distinctive part of the console output during startup?
java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.Banner.Mode;

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.setBannerMode(Mode.OFF);
        app.run(args);
        System.out.println("Application finished startup.");
    }
}
Q643 medium code error
What error occurs when accessing `/users/123` with the following controller?
java
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping("/{userId}")
    public String getUser(@PathVariable String id) {
        return "User ID: " + id;
    }
}
Q644 medium code output
What is the output of this code when `App` is executed? (The display name of the context may vary slightly.)
java
import org.springframework.beans.BeansException;
import org.springframework.context.*;
import org.springframework.stereotype.Component;

@Component
class MyContextAwareBean implements ApplicationContextAware {
    private ApplicationContext ctx;
    public MyContextAwareBean() { System.out.println("1. Ctor"); }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx = applicationContext;
        System.out.println("2. setApplicationContext called.");
    }
    public boolean isContextSet() { return ctx != null; }
}
@ComponentScan
public class App {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);
        MyContextAwareBean bean = context.getBean(MyContextAwareBean.class);
        System.out.println("3. Context set: " + bean.isContextSet());
        context.close();
    }
}
Q645 medium code output
What will be the HTTP status code and response body when a GET request is made to `/simulate/error` based on the given Spring Boot code?
java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
class ErrorSimulatorController {
    @GetMapping("/simulate/error")
    public String simulateError() {
        throw new RuntimeException("A simulated unexpected error occurred");
    }
}

@RestControllerAdvice
class MyGlobalExceptionHandler {
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
        return new ResponseEntity<>("Application Error: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Q646 medium
In Thymeleaf, what is the primary purpose of the `th:object` attribute on a `<form>` tag?
Q647 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;
import org.springframework.context.annotation.Scope;

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

class MyCounter { /* Simple class */ }

@Configuration
class AppConfig {
    @Bean
    @Scope("prototype")
    public MyCounter prototypeCounter() {
        return new MyCounter();
    }
}
Q648 medium
Which annotation allows you to map an HTTP GET request to a specific method within a `@RestController`?
Q649 medium
What is the primary advantage of using specialized annotations like `@GetMapping` or `@PostMapping` over using `@RequestMapping(method = RequestMethod.GET)`?
Q650 medium code output
What is the HTTP response body when making a GET request to `/status`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class StatusController {

    @GetMapping("/status")
    @ResponseBody
    public String getStatus() {
        return "{\"status\": \"UP\"}";
    }
}
Q651 medium code error
What error will be triggered when a GET request is made to `/api/posts` with the following code due to bidirectional relationships without proper Jackson annotations?
java
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
public class MyController {
    @GetMapping("/api/posts")
    public List<Post> getPosts() {
        User u1 = new User("Alice");
        Post p1 = new Post("First Post", u1);
        u1.addPost(p1); 
        return List.of(p1);
    }

    static class User {
        private String name; private List<Post> posts = new java.util.ArrayList<>();
        public User(String name) { this.name = name; } public String getName() { return name; }
        public void addPost(Post post) { this.posts.add(post); } public List<Post> getPosts() { return posts; }
    }

    static class Post {
        private String title; private User author;
        public Post(String title, User author) { this.title = title; this.author = author; } 
        public String getTitle() { return title; } public User getAuthor() { return author; }
    }
}
Q652 medium
What happens if an `@Autowired` field is annotated with `@Qualifier("nonExistentBean")`, and no bean with that specific qualifier name exists in the application context?
Q653 medium code error
Given the following Spring component and configuration, what error will occur at startup?
java
java
@Component
public class ItemProcessor {
    @Value("${item.prices}")
    private List<Double> prices;

    public List<Double> getPrices() {
        return prices;
    }
}


properties
# application.properties
item.prices=10.5,twenty,30.0
Q654 medium code output
A Spring Boot application with the given Dockerfile is started. Inside the application, which value will `spring.datasource.url` resolve to if no other configuration (e.g., `application.properties`) specifies it?
dockerfile
FROM openjdk:17-jre-slim
WORKDIR /app
COPY target/my-app.jar app.jar
ENV SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/mydb
CMD ["java", "-jar", "app.jar"]
Q655 medium code output
Assuming a default Spring Boot setup with Thymeleaf, what is the expected HTTP response status code and body when making a GET request to `/hello`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MyViewController {

    @GetMapping("/hello")
    public String sayHello() {
        return "greeting";
    }
}
Q656 medium code output
What does this code print to the console when `App` is executed?
java
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Component;

@Component
class MyBean implements DisposableBean {
    public MyBean() { System.out.println("1. Ctor"); }
    @PreDestroy public void preDestroy() { System.out.println("2. @PreDestroy"); }
    @Override
    public void destroy() { System.out.println("3. DisposableBean.destroy"); }
}
@ComponentScan
public class App {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);
        System.out.println("4. Context Initialized");
        context.close();
    }
}
Q657 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;
import org.springframework.dao.BadSqlGrammarException;
import java.sql.SQLException;

@Repository
class DataAccessRepository {
    public void executeBadSql() {
        // JdbcTemplate would typically do this translation, we simulate it here.
        throw new BadSqlGrammarException("SELECT * FROM non_existent_table", "SELECT * FROM non_existent_table", new SQLException("Table not found"));
    }
}

@Service
class BusinessService {
    @Autowired DataAccessRepository repo;
    public void performOperation() {
        try {
            repo.executeBadSql();
        } catch (Exception e) {
            System.out.println("Caught exception: " + e.getClass().getSimpleName());
        }
    }
}

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
        BusinessService service = context.getBean(BusinessService.class);
        service.performOperation();
        context.close();
    }
}
Q658 medium code error
An application has a `@Repository` class located in `com.app.data` package. If the `@SpringBootApplication` or `@ComponentScan` annotation specifies `basePackages = "com.app.service"`, what error will be encountered during application startup when `UserService` tries to autowire `UserRepository`?
java
package com.app.data;
import org.springframework.stereotype.Repository;

@Repository
public class UserRepository {
    public String findUserById(Long id) { return "User " + id; }
}

package com.app.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.app.data.UserRepository;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public String getUser(Long id) { return userRepository.findUserById(id); }
}
// Assuming @SpringBootApplication(scanBasePackages = "com.app.service")
Q659 medium code error
What will be the outcome when trying to access the `/greet` endpoint of this Spring Boot application?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;

@Controller
public class MyController {

    @GetMapping("/greet")
    public String greetUser(Model model) {
        model.addAttribute("name", "World");
        return "greeting"; 
    }
}
Q660 medium code output
What is the output when a Spring Boot application retrieves a `@Service` bean by its custom name from the `ApplicationContext`? (Assume standard Spring Boot setup and necessary imports.)
java
import org.springframework.stereotype.Service;
import org.springframework.context.ApplicationContext;

@Service("customReporter")
class ReportService {
    public String generateReport() { return "Report Generated"; }
}

// In a @SpringBootApplication's CommandLineRunner, after autowiring ApplicationContext:
// ApplicationContext context;
// ReportService service = context.getBean("customReporter", ReportService.class);
// System.out.println(service.generateReport());
← Prev 3132333435 Next → Page 33 of 49 · 971 questions