🌱 Spring Boot MCQ Questions – Page 22
Questions 421–440 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsWhat 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.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
interface MessageService { String send(); }
@Component("emailService")
class EmailService implements MessageService { @Override public String send() { return "Sending email notification."; } }
@Component("smsService")
class SmsService implements MessageService { @Override public String send() { return "Sending SMS notification."; } }
@Component
class NotificationSender implements CommandLineRunner {
@Autowired
@Qualifier("emailService")
private MessageService service;
@Override
public void run(String... args) { System.out.println(service.send()); }
}
@SpringBootApplication
public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
An application configures a `DataSource` for JPA, which is then used by an `EntityManagerFactory` and ultimately by a `@Repository`. If the `DataSource` is configured with a non-existent JDBC driver class name, what error will occur during application startup?
java
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import javax.sql.DataSource;
@Configuration
public class JpaConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("non.existent.Driver"); // This line causes the error
dataSource.setUrl("jdbc:h2:mem:testdb");
dataSource.setUsername("sa");
dataSource.setPassword("");
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan("com.example.domain");
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
return em;
}
}
// Assuming a @Repository class uses this EntityManagerFactory.
Consider a scenario where a DELETE request is made to `/api/reports/summary`. What HTTP status code and body would be returned by this Spring Boot controller method if the `reportService.clearSummary()` call succeeds?
java
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/reports")
public class ReportController {
private ReportService reportService;
// Constructor injected reportService
@DeleteMapping("/summary")
public void clearSummary() {
reportService.clearSummary();
// No explicit @ResponseStatus, no return value
}
}
If the Spring Boot application above is packaged as `myapp.jar` and executed as `java -jar myapp.jar --spring.profiles.active=dev`, what will be the output from the `CommandLineRunner`?
java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.boot.CommandLineRunner;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Profile("dev")
@Bean
public CommandLineRunner devRunner() {
return args -> {
System.out.println("Running in Development Profile!");
};
}
@Profile("!dev") // For any profile NOT dev, or no profile
@Bean
public CommandLineRunner defaultRunner() {
return args -> {
System.out.println("Running in Default Profile.");
};
}
}
What will be the outcome when running this Spring Boot application?
java
public interface MessageService {
String getMessage();
}
@Service("emailService")
public class EmailService implements MessageService {
@Override
public String getMessage() { return "Email message"; }
}
@Service("smsService")
public class SmsService implements MessageService {
@Override
public String getMessage() { return "SMS message"; }
}
@Component
public class Notifier {
@Autowired
private MessageService messageService; // Ambiguity here
public void notifyUser() {
System.out.println(messageService.getMessage());
}
}
What is the primary difference between `@Controller` and `@RestController` in Spring Boot applications, especially when building RESTful APIs?
What happens if a `@PathVariable` in a Spring Boot controller method is declared as `int` but the corresponding URI segment contains a non-numeric string?
To change the base package for component scanning when using `@SpringBootApplication`, which attribute should be used?
What is the console output when a GET request is made to `/data` in this Spring Boot application?
java
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
System.out.println("Interceptor: Pre-handle");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
System.out.println("Interceptor: Post-handle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
System.out.println("Interceptor: After-completion");
}
}
@Configuration
class WebConfig implements WebMvcConfigurer {
private final MyInterceptor myInterceptor;
public WebConfig(MyInterceptor myInterceptor) { this.myInterceptor = myInterceptor; }
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/data");
}
}
@RestController
class DataController {
@GetMapping("/data")
public String getData() {
System.out.println("Controller: Processing Data");
return "Data";
}
}
What does the following Spring Boot related JWT code print after successfully parsing a token and extracting a claim?
java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
public class ClaimExtractor {
public static void main(String[] args) {
Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
String jwt = Jwts.builder()
.setSubject("adminUser")
.claim("customRole", "SUPER_ADMIN")
.signWith(key)
.compact();
Claims claims = Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(jwt)
.getBody();
System.out.println(claims.get("customRole"));
}
}
Consider an interface `NotificationService` with two implementations: `EmailNotificationService` and `SMSNotificationService`. Both are Spring components. How would you inject specifically the `EmailNotificationService` into another component?
Given the Spring Boot controller method below, what type of error will occur?
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 MyController {
@GetMapping("/immutable-test")
public ResponseEntity<String> testImmutability() {
ResponseEntity<String> response = ResponseEntity.ok("Initial Body");
response.getHeaders().add("X-Custom-Header", "New Value");
return response;
}
}
What is the output of this code snippet, assuming `userRepository` is a JpaRepository and initially contains no users?
java
public class UserService {
private UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public String updateOrCreateUser(Long id, String name, String email) {
User user = userRepository.findById(id).orElse(new User());
user.setName(name);
user.setEmail(email);
userRepository.save(user);
return user.getId() != null ? "User saved with ID: " + user.getId() : "New user created";
}
}
// In a test context or main method:
UserService service = new UserService(userRepository);
String result = service.updateOrCreateUser(null, "David", "david@example.com");
System.out.println(result);
What type of error will occur when Spring tries to initialize the `MyService` bean?
java
import org.springframework.stereotype.Component;
@Component
public class MyService {
private final String serviceConfig;
// Spring tries to find a bean of type String, but none exists by default
public MyService(String serviceConfig) {
this.serviceConfig = serviceConfig;
}
public String getConfig() {
return "Config: " + serviceConfig;
}
}
What is the HTTP response status code when making a `GET` request to `/submit-form` with the following controller?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class FormController {
@PostMapping("/submit-form")
@ResponseBody
public String processForm() {
return "Form submitted successfully!";
}
}
What error will occur when Spring attempts to inject dependencies into `ServiceA`?
java
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
@Component
public class ServiceA {
@Autowired
private NonExistentService nonExistentService;
public void doWork() {
// ...
}
}
What is the output of this code when accessing the '/test' endpoint?
java
import org.springframework.web.bind.annotation.*;
@RestController
public class MyController {
@GetMapping("/test")
public String testMethod() {
throw new RuntimeException("An unexpected error occurred!");
}
@ExceptionHandler(RuntimeException.class)
public String handleRuntimeException(RuntimeException ex) {
return "Error caught: " + ex.getMessage();
}
}
What is the primary error when Spring Boot attempts to start this application?
java
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Repository;
@Service
public class UserService {
private UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
// UserRepository.java (in the same package)
// Missing @Repository or @Component annotation
public class UserRepository {
public String findById(Long id) {
return "DB: User " + id;
}
}
What is the HTTP response body when a GET request is made to `/orders/101/items/5005`?
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 OrderController {
@GetMapping("/orders/{userId}/items/{itemId}")
public String getOrderItem(@PathVariable Long userId, @PathVariable Long itemId) {
return "Order details for User " + userId + ", Item " + itemId;
}
}
What is the output of this code when accessing '/info'?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
@RestController
public class InfoController {
@GetMapping("/info")
public String getInfo() {
throw new UnsupportedOperationException("Feature is not available");
}
@ExceptionHandler(UnsupportedOperationException.class)
@ResponseStatus(HttpStatus.NOT_IMPLEMENTED)
public String handleUnsupportedOperation(UnsupportedOperationException ex) {
return "Status 501: " + ex.getMessage();
}
}