🌱 Spring Boot MCQ Questions – Page 5

Questions 81–100 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q81 medium code error
What error will occur during Spring Boot application startup for the given component?
java
java
@Component
public class ReportGenerator {
    @Value("#{myDataSource.connectionString}")
    private String dbConnectionString;

    public String getDbConnectionString() {
        return dbConnectionString;
    }
}

// Assume 'myDataSource' bean is NOT defined in the application context.
Q82 medium code output
What is the output of this code?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@SpringBootApplication
public class MyApplication {
    static class MySingletonCounter { private int count = 0; public int incrementAndGet() { return ++count; } }
    @Bean // Default scope is singleton
    public MySingletonCounter singletonCounter() { return new MySingletonCounter(); }

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(MyApplication.class, args);
        MySingletonCounter c1 = ctx.getBean(MySingletonCounter.class);
        MySingletonCounter c2 = ctx.getBean(MySingletonCounter.class);
        System.out.println("C1: " + c1.incrementAndGet());
        System.out.println("C2: " + c2.incrementAndGet());
    }
}
Q83 medium code output
What is the HTTP response body when a GET request is made to `/users/john_doe`?
java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @GetMapping("/users/{username}")
    public String getUserProfile(@PathVariable String username) {
        return "Profile of " + username + " accessed.";
    }
}
Q84 medium code output
What does this code print to the console?
java
package com.example;

import jakarta.persistence.*;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;

@Entity
public class Product {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;

    public Product() {}
    public Product(Long id, String name, double price) { this.id = id; this.name = name; this.price = price; }
    public String getName() { return name; }
    public double getPrice() { return price; }
}

interface ProductRepository extends JpaRepository<Product, Long> {
    @Query("SELECT p FROM Product p WHERE p.name LIKE %:keyword%")
    List<Product> findProductsByNameContainingJPQL(@Param("keyword") String keyword);
}

// Assume ProductRepository is autowired as 'productRepository'
// And the database contains:
// Product(id=1, name='Laptop Pro', price=1500.00)
// Product(id=2, name='Gaming Laptop', price=1800.00)
// Product(id=3, name='Desktop PC', price=1000.00)
List<Product> products = productRepository.findProductsByNameContainingJPQL("Laptop");
System.out.println(products.size());
Q85 medium code output
Given a `User` entity and `UserRepository` (JpaRepository), what does this test code print to the console?
java
import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

@DataJpaTest
class UserRepositoryTest {
    @Autowired
    private UserRepository userRepository;

    @Test
    void testSaveAndFindUser() {
        userRepository.save(new User("Alice"));
        System.out.print(userRepository.count());
    }
}
Q86 medium code output
What is the output when accessing `/hello` without the `user` parameter?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@RestController
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }

    @GetMapping("/hello")
    public String sayHello(@RequestParam(required = false) String user) {
        if (user == null) {
            return "Hello there!";
        }
        return "Hello, " + user + "!";
    }
}
Q87 medium
For a Spring Boot web application, which specific type of `ApplicationContext` is typically used to handle web-related concerns, such as request dispatching and session management?
Q88 medium
What is the effect of setting `proxyBeanMethods = false` on an `@Configuration` class containing `@Bean` methods?
Q89 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
class MyProductRepository {
    public MyProductRepository() {
        System.out.println("MyProductRepository initialized.");
    }
}

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
        context.getBean(MyProductRepository.class);
        context.close();
    }
}
Q90 medium code output
What does this code print to the console?
java
package com.example;

import jakarta.persistence.*;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;

@Entity
public class Product {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;

    public Product() {}
    public Product(Long id, String name, double price) { this.id = id; this.name = name; this.price = price; }
    public String getName() { return name; }
    public double getPrice() { return price; }
}

interface ProductRepository extends JpaRepository<Product, Long> {
    @Query(value = "SELECT * FROM product WHERE name LIKE CONCAT('%', ?1, '%') ORDER BY id", nativeQuery = true)
    List<Product> findProductsByNameContainingNative(String keyword);
}

// Assume ProductRepository is autowired as 'productRepository'
// And the database contains:
// Product(id=1, name='SSD 1TB', price=100.00)
// Product(id=2, name='HDD 2TB', price=80.00)
// Product(id=3, name='SSD 500GB', price=60.00)
// Assume 'product' is the correct table name.
List<Product> products = productRepository.findProductsByNameContainingNative("SSD");
System.out.println(products.get(0).getName());
Q91 medium code error
Consider the following Spring Boot configuration. What error will occur during application context initialization?
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean(initMethod = "nonExistentInitMethod")
    public String myStringBean() {
        return "Hello";
    }
}
Q92 medium code output
Given the following component in a Spring Boot application with `@EnableScheduling`. If the `app.cron.expression` property in `application.properties` is initially set to `0/5 * * * * *` (every 5 seconds) but is updated to `0/10 * * * * *` (every 10 seconds) *while the application is running*, what will be the execution frequency of `dynamicCronTask`?
java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class DynamicCronScheduler {

    @Scheduled(cron = "${app.cron.expression}")
    public void dynamicCronTask() {
        System.out.println(System.currentTimeMillis() + " - Dynamic Cron Task executed.");
    }
}
Q93 medium code error
If a Spring Boot application using Thymeleaf does *not* include the `spring-boot-starter-thymeleaf` dependency, what would be the typical runtime error when a controller returns a view name like `index`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;

@Controller
public class IndexController {

    @GetMapping("/index")
    public String showIndex(Model model) {
        model.addAttribute("title", "My Page");
        return "index"; // Assumes index.html exists, but no Thymeleaf starter is present
    }
}
Q94 medium code output
Given the Spring Boot application above, if it's packaged as `myapp.jar` but the `spring-boot-starter-web` dependency (which typically includes an embedded Tomcat server) was accidentally *excluded* from the build, what will be the most likely immediate output during execution with `java -jar myapp.jar`?
java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;

@SpringBootApplication
@RestController
public class MyApplication {

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

    @GetMapping("/")
    public String hello() {
        return "Hello, Spring Boot!";
    }
}
Q95 medium code output
Given the following `application.yml` for a Eureka client application, what will be the format of the instance ID registered with the Eureka server?
yaml
spring:
  application:
    name: payment-service

server:
  port: 8082

eureka:
  instance:
    instance-id: ${spring.application.name}:${random.value}
Q96 medium code error
What error will occur when accessing `/api/order?code=INVALID` with the following Spring Boot controller?
java
import org.springframework.web.bind.annotation.*;

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

    public enum OrderStatus { PENDING, SHIPPED, DELIVERED }

    @GetMapping("/order")
    public String getOrder(@RequestParam(required = false) OrderStatus code) {
        return "Order Status: " + (code != null ? code.name() : "N/A");
    }
}
Q97 medium code output
What is the output of this code?
java
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Collections;

public class SecureService {
    @PreAuthorize("isAuthenticated()")
    public String getDashboard() { return "Dashboard"; }
}

public class TestRunner {
    public static void main(String[] args) {
        SecurityContextHolder.getContext().setAuthentication(
            new UsernamePasswordAuthenticationToken("guest", "pass", Collections.emptyList())
        );
        SecureService service = new SecureService();
        try { System.out.println(service.getDashboard()); }
        catch (Exception e) { System.out.println(e.getClass().getSimpleName()); }
    }
}
Q98 medium code error
This Spring Boot application has two controller methods mapped to the same path. What error will occur when the application attempts to start?
java
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class ConflictController {
    @GetMapping("/data")
    public String getData() {
        return "Data from method 1";
    }

    @GetMapping("/data")
    public String getConflictingData() {
        return "Data from method 2";
    }
}
Q99 medium code error
What is the expected error when compiling this Spring Boot component?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Component
public class MyComponent {
    @Autowired
    private final DependentService dependentService; // ERROR: final field not initialized

    public String doWork() {
        return dependentService.performTask();
    }
}

@Service
class DependentService {
    public String performTask() {
        return "Task done.";
    }
}
Q100 medium code output
Considering the `FeignClient` setup and a call with query parameters, what will be printed?
java
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(name = "searchService", url = "http://localhost:8085")
interface SearchServiceClient {
    @GetMapping("/search")
    String searchProducts(@RequestParam("q") String query, @RequestParam("page") int page);
}

public class TestApplication {
    public static void main(String[] args) {
        SearchServiceClient client = (q, p) -> "Searching for '" + q + "' on page " + p;
        System.out.println(client.searchProducts("laptop", 2));
    }
}
← Prev 34567 Next → Page 5 of 49 · 971 questions