🌱 Spring Boot MCQ Questions – Page 12

Questions 221–240 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q221 medium
When defining a bean using a `@Bean` method, how can you associate a specific qualifier name with it so it can be targeted by `@Qualifier` at the injection point?
Q222 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.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

@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> {
    @Modifying
    @Transactional
    @Query(value = "DELETE FROM product WHERE id = :id", nativeQuery = true)
    int deleteProductByIdNative(@Param("id") Long id);
}

// Assume ProductRepository is autowired as 'productRepository'
// And the database contains: Product(id=1, name='Speaker', price=150.00)
// Assume 'product' is the correct table name.
int deletedCount = productRepository.deleteProductByIdNative(1L);
System.out.println(deletedCount);
Q223 medium code output
What will be the output of the following Spring Boot application?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Scope;

@Component
@Scope("prototype")
class Counter {
    private int count = 0;

    public void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        var context = SpringApplication.run(MyApplication.class, args);
        Counter counter1 = context.getBean(Counter.class);
        counter1.increment();
        counter1.increment();

        Counter counter2 = context.getBean(Counter.class);
        counter2.increment();

        System.out.println("Counter1: " + counter1.getCount());
        System.out.println("Counter2: " + counter2.getCount());
    }
}
Q224 medium code error
What kind of error will occur during Spring application startup with the given code?
java
java
@Component
public class FeatureFlag {
    @Value("#{null}")
    private boolean enabled;

    public boolean isEnabled() {
        return enabled;
    }
}
Q225 medium code error
Given a Spring Data JPA repository interface with a custom query method, what error will occur during application startup if the method name `findByUserName` does not correctly map to a property named `userName` (instead of `username`) on the `User` entity?
java
package com.example.entity;
import jakarta.persistence.Entity; import jakarta.persistence.Id; @Entity public class User { @Id private Long id; private String username; /* getters/setters */ }

package com.example.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByUserName(String user_name); // Incorrect: Should be findByUsername
}

package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.repository.UserRepository;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    public User getUserByUsername(String username) { return userRepository.findByUserName(username).orElse(null); }
}
// Assuming @EnableJpaRepositories is present.
Q226 medium
Which annotation is used to bind a web request parameter (e.g., `?name=value&age=30`) from the query string to a method parameter in a Spring Boot GET request?
Q227 medium code error
What will be the outcome when running this Spring Boot application?
java
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Service("serviceAlpha")
public class ServiceAlpha {
    public String identify() { return "I am Alpha"; }
}

@Service("serviceBeta")
public class ServiceBeta {
    public String identify() { return "I am Beta"; }
}

@Component
public class Processor {
    @Autowired
    @Qualifier("serviceBeta") // Trying to inject a ServiceBeta bean
    private ServiceAlpha service; // into a ServiceAlpha type field. Type mismatch.

    public void execute() {
        System.out.println(service.identify());
    }
}
Q228 medium code error
What will be the error if a client attempts a GET request to `/api/submit`?
java
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class SubmissionController {
    @RequestMapping("/submit")
    public String submitForm(@RequestBody String data) {
        return "Form submitted with data: " + data;
    }
}
Q229 medium code output
What is the HTTP response body when a GET request is made to '/items/books/123'?
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 ItemController {
    @GetMapping("/items/{category}/{id}")
    public String getItemDetails(@PathVariable String category, @PathVariable Long id) {
        return "Category: " + category + ", ID: " + id;
    }
}
Q230 medium code error
What kind of error will occur when the following Spring Boot code is compiled?
java
import org.springframework.http.ResponseEntity;

public class NoContentTest {
    public ResponseEntity<Void> createNoContentResponse() {
        return ResponseEntity.noContent().body("This should not be here").build();
    }
}
Q231 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.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.List;

interface ReportGenerator { void generate(); }

@Component
class PdfReportGenerator implements ReportGenerator { @Override public void generate() { System.out.println("Generating PDF report."); } }

@Component
class CsvReportGenerator implements ReportGenerator { @Override public void generate() { System.out.println("Generating CSV report."); } }

@Component
class ReportProcessor implements CommandLineRunner {
    @Autowired
    private List<ReportGenerator> generators;
    @Override
    public void run(String... args) {
        for (ReportGenerator generator : generators) {
            generator.generate();
        }
    }
}

@SpringBootApplication
public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
Q232 medium code output
What is the `Content-Type` header and body returned by the `getPlainMessage` method when a POST request is made to `/message` with the body `"Hello World"` (Accept: */*)?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

@RestController
@RequestMapping("/message")
class MessageController {
    @PostMapping(produces = MediaType.TEXT_PLAIN_VALUE)
    public ResponseEntity<String> getPlainMessage(@RequestBody String inputMessage) {
        return new ResponseEntity<>("You said: " + inputMessage, HttpStatus.CREATED);
    }
}
Q233 medium code output
What happens when you try to create a `SecretKey` using `Keys.hmacShaKeyFor` with a string that is too short for HMAC-SHA256, and then use it to sign a JWT?
java
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.WeakKeyException;
import java.security.Key;

public class WeakKeyDemo {
    public static void main(String[] args) {
        String shortSecret = "abc"; // Too short for HS256 (min 256 bits/32 bytes)
        try {
            Key key = Keys.hmacShaKeyFor(shortSecret.getBytes());
            String jwt = Jwts.builder()
                    .setSubject("user")
                    .signWith(key)
                    .compact();
            System.out.println("JWT created: " + jwt.startsWith("eyJ"));
        } catch (WeakKeyException e) {
            System.out.println("WeakKeyException caught: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("Other exception: " + e.getClass().getSimpleName());
        }
    }
}
Q234 medium code error
What error will be thrown when this Spring Boot application attempts to start?
java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyConfigComponent {
    @Value("${app.non.existent.property}") // This property is not defined
    private String someValue;

    public String getSomeValue() {
        return someValue;
    }
}
Q235 medium code output
What will be the expected HTTP status code returned by the gateway for an incoming request to `/restricted` if the current time is `2023-10-27T10:00:00Z`?
java
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.ZonedDateTime;

@Configuration
public class GatewayConfig {
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("time_restricted_route", r -> r.path("/restricted")
                        .before(ZonedDateTime.parse("2023-10-27T09:00:00Z"))
                        .uri("http://localhost:8082"))
                .build();
    }
}
Q236 medium code output
Given this Dockerfile, if you run `docker build --build-arg APP_VERSION=1.2.3 -t my-app .`, what would be the name of the final JAR file copied into the image?
dockerfile
FROM maven:3.8.5-openjdk-17 AS build
WORKDIR /app
COPY pom.xml .
COPY src ./src
RUN mvn package -DskipTests

FROM openjdk:17-jre-slim
WORKDIR /app
ARG APP_VERSION=0.0.1-SNAPSHOT
COPY --from=build /app/target/my-app-${APP_VERSION}.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]
Q237 medium
How can you make a `@RequestParam` optional without providing a `defaultValue`?
Q238 medium
What is the default scope for a bean registered using the `@Service` annotation in a Spring Boot application?
Q239 medium code error
What error occurs if you attempt to call `refresh()` on an already initialized and refreshed Spring ApplicationContext?
java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;

@Configuration
class AppConfig {}

public class RefreshApp {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        // Context is already refreshed by the constructor
        context.refresh(); // Attempt to refresh again
    }
}
Q240 medium
How does `@RestController` typically determine the content type of the response (e.g., JSON or XML) when an object is returned?
← Prev 1011121314 Next → Page 12 of 49 · 971 questions