🌱 Spring Boot MCQ Questions – Page 2
Questions 21–40 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsWhat is the primary purpose of the @PostConstruct annotation in the Spring bean lifecycle?
What is the expected error when starting a Spring Boot application with this configuration?
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MyComponent myNullBean() {
// A bean method is not allowed to return null
return null;
}
}
public class MyComponent {
public String getValue() { return "Hello"; }
}
What is the output of this code snippet, given a database with 5 `Product` entities?
java
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
interface ProductRepository extends JpaRepository<Product, Long> {
Page<Product> findAll(Pageable pageable);
}
// Assuming Product and ProductRepository are properly defined and wired
// and 'productRepository' is an injected instance.
// Simulate DB content: 5 Product entities.
public class TestService {
ProductRepository productRepository;
public TestService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
public int getTotalPagesForQuery() {
Pageable pageable = PageRequest.of(0, 2); // page 0, size 2
Page<Product> productPage = productRepository.findAll(pageable);
return productPage.getTotalPages();
}
}
// In a conceptual main method or test:
// System.out.println(new TestService(productRepositoryMock).getTotalPagesForQuery());
What is the expected output when attempting to persist the `User` entity with a `null` email?
java
import jakarta.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true)
private String email;
public User() {}
public User(String email) { this.email = email; }
}
// Assume userRepository is injected and available
// Assume transaction context is active
try {
userRepository.save(new User(null));
System.out.println("User saved successfully.");
} catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
}
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.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Collections;
public class SecureService {
@PreAuthorize("hasRole('GUEST') or hasRole('USER')")
public String getPublicContent() { return "Public Content"; }
}
public class TestRunner {
public static void main(String[] args) {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("guest", "pass", Collections.singletonList(new SimpleGrantedAuthority("ROLE_GUEST")))
);
SecureService service = new SecureService();
try { System.out.println(service.getPublicContent()); }
catch (Exception e) { System.out.println(e.getClass().getSimpleName()); }
}
}
What is the output when accessing `/greet?name=World`?
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("/greet")
public String greetUser(@RequestParam String name) {
return "Hello, " + name + "!";
}
}
What does it mean for a DELETE operation in a Spring Boot REST API to be idempotent?
When using Spring Data JPA, which method from a `JpaRepository` interface is commonly used to delete an entity by its primary key ID?
What error will this custom `BeanPostProcessor` cause when the Spring application context initializes?
java
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
@Component
public class NullifyingPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (beanName.equals("myService")) {
return null; // Returning null for a regular bean
}
return bean;
}
}
@Component("myService")
class MyService {}
When a `@Bean` method within a `@Configuration` class requires other Spring-managed dependencies, how does Spring Boot typically provide them?
Given the Spring Boot controller above, what will be the HTTP response body when a GET request is made to `/config` (without any query parameters)?
java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SettingsController {
@GetMapping("/config")
public String getConfig(@RequestParam(defaultValue = "default_mode") String mode) {
return "Current mode: " + mode;
}
}
Consider the following Spring Boot application setup. What error will occur when this application attempts to start and retrieve `myStringBean`?
java
import org.springframework.context.annotation.Bean;
public class MyBeanProducer {
@Bean
public String myStringBean() {
return "Hello";
}
}
// Main application class:
// ConfigurableApplicationContext context = SpringApplication.run(MyApplication.class);
// context.getBean(String.class);
If you have a `UserRepository` annotated with `@Repository`, how would you typically use it within a `UserService` (annotated with `@Service`) to perform data operations?
What is the output of this code when the `main` method of `MyApplication` is executed?
java
// src/main/java/com/example/demo/MyApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
// src/main/java/com/example/demo/MyService.java
package com.example.demo;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
class MyService {
@PostConstruct
public void init() {
System.out.println("MyService Initialized");
}
}
What is the console output for a GET request to `/admin/reports` with the given interceptor configuration?
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 AdminInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
System.out.println("AdminInterceptor: Accessing " + request.getRequestURI());
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { /* empty */ }
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { /* empty */ }
}
@Configuration
class AdminWebConfig implements WebMvcConfigurer {
private final AdminInterceptor adminInterceptor;
public AdminWebConfig(AdminInterceptor adminInterceptor) { this.adminInterceptor = adminInterceptor; }
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(adminInterceptor)
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin/login", "/admin/public");
}
}
@RestController
class AdminController {
@GetMapping("/admin/reports")
public String getReports() {
System.out.println("Controller: Generating reports");
return "Reports";
}
@GetMapping("/admin/login")
public String login() { return "Login"; }
}
What is the output of this code?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
@Component class MyComponent {
public String greet() { return "Hello from MyComponent!"; }
}
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
var context = SpringApplication.run(DemoApplication.class, args);
var component = context.getBean(MyComponent.class);
System.out.println(component.greet());
}
}
By default, how many instances of a Spring bean are created and managed by the Spring `ApplicationContext` for a given bean definition, assuming no specific scope is declared?
What is the expected outcome when this Spring Boot application starts?
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
interface MyInterface {}
@Component("firstImpl")
class MyImplementation1 implements MyInterface {}
@Component("secondImpl")
class MyImplementation2 implements MyInterface {}
@Component
class MyConsumer {
@Autowired
private MyInterface service;
}
A client sends a PUT request to `/api/items/abc` with a valid JSON body. What type of error will occur during request processing?
java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/items")
public class ItemController {
@PutMapping("/{itemId}")
public ResponseEntity<Item> updateItem(@PathVariable Long itemId, @RequestBody Item itemDetails) {
// Logic to update item
return ResponseEntity.ok(itemDetails);
}
}
// Assume Item class exists
Which of the following annotations would you use on a method to specify that it should be executed just before a bean is destroyed by the Spring container?