🌱 Spring Boot MCQ Questions – Page 8
Questions 141–160 of 971 total — Spring Boot interview practice
▶ Practice All Spring Boot QuestionsWhat is the output of this code when `App` is executed?
java
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.*;
class MyInitBean implements InitializingBean {
public MyInitBean() { System.out.println("1. Ctor"); }
@PostConstruct public void postConstruct() { System.out.println("2. @PostConstruct"); }
@Override
public void afterPropertiesSet() { System.out.println("3. afterPropertiesSet"); }
public void customInit() { System.out.println("4. customInitMethod"); }
}
@Configuration
public class App {
@Bean(initMethod = "customInit") public MyInitBean myInitBean() { return new MyInitBean(); }
public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class); context.close(); }
}
What is the output of this code?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
interface MyInterface { String getID(); }
@Component("implA") class MyImplA implements MyInterface { public String getID() { return "A"; } }
@Component("implB") class MyImplB implements MyInterface { public String getID() { return "B"; } }
@SpringBootApplication
public class App5 {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(App5.class, args);
try {
ctx.getBean(MyInterface.class);
} catch (Exception e) {
System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage().split("\n")[0]);
}
}
}
What error will occur when the `/api/data` endpoint is accessed, attempting to return an instance of `MyResponse`?
java
import org.springframework.web.bind.annotation.*;
@RestController
public class MyController {
@GetMapping("/api/data")
public MyResponse getData() {
return new MyResponse("Hello");
}
static class MyResponse { // Missing public getter for 'message'
private String message;
public MyResponse(String message) { this.message = message; }
}
}
What error will occur when accessing `/api/product?id=abc` with the following Spring Boot controller?
java
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class ProductController {
@GetMapping("/product")
public String getProduct(@RequestParam int id) {
return "Product ID: " + id;
}
}
What is the HTTP response body when a GET request is made to `/files/image_01.jpg`?
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 FileController {
@GetMapping("/files/{fileName:[a-zA-Z0-9]+}.txt")
public String getFileContent(@PathVariable String fileName) {
return "Content of " + fileName + ".txt";
}
}
What is the expected error when starting this Spring Boot application due to the configuration of `ServiceA` and `ServiceB`?
java
import org.springframework.stereotype.Service;
@Service
public class ServiceA {
private final ServiceB serviceB;
public ServiceA(ServiceB serviceB) {
this.serviceB = serviceB;
}
public String getInfo() { return "From A"; }
}
@Service
public class ServiceB {
private final ServiceA serviceA;
public ServiceB(ServiceA serviceA) {
this.serviceA = serviceA;
}
public String getInfo() { return "From B"; }
}
A user named "user" with role "USER" logs into the application and attempts to access the `/admin/task` endpoint. What is the typical HTTP status code and response body content they will receive?
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withUsername("user").password("{noop}password").roles("USER").build();
return new InMemoryUserDetailsManager(user);
}
}
@Service
public class AdminService { public String performAdminTask() { return "Admin task performed."; } }
@RestController
public class AdminController {
private final AdminService adminService;
public AdminController(AdminService adminService) { this.adminService = adminService; }
@GetMapping("/admin/task")
@PreAuthorize("hasRole('ADMIN')")
public String getAdminTask() { return adminService.performAdminTask(); }
}
What HTTP status code is expected when attempting to access a non-existent endpoint with MockMvc?
java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(controllers = TestController.class)
class TestControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testNonExistentEndpoint() throws Exception {
mockMvc.perform(get("/api/nonexistent"))
.andExpect(status().isNotFound());
}
}
// Assuming TestController has:
// @RestController
// class TestController {
// // No mapping for /api/nonexistent
// @GetMapping("/api/hello")
// public String hello() { return "Hello MockMvc!"; }
// }
What is the output when '/process/data' is accessed, and no `DataAccessException` handler is defined?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.dao.DataAccessException;
@RestController
public class ProcessingController {
@GetMapping("/process/data")
public String processData() {
throw new DataAccessException("Database connection lost") {};
}
@ExceptionHandler(RuntimeException.class)
public String handleRuntimeException(RuntimeException ex) {
return "General Error Handler: " + ex.getMessage();
}
}
To enable automatic validation of a form object passed into a Spring MVC controller method using standard JSR-303/380 annotations (like `@NotNull`, `@Size`), which annotation must be placed directly before the object parameter in the method signature?
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("isAuthenticated() and hasRole('EMPLOYEE')")
public String getEmployeeBenefits() { return "Employee Benefits"; }
}
public class TestRunner {
public static void main(String[] args) {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("manager", "pass", Collections.singletonList(new SimpleGrantedAuthority("ROLE_MANAGER")))
);
SecureService service = new SecureService();
try { System.out.println(service.getEmployeeBenefits()); }
catch (Exception e) { System.out.println(e.getClass().getSimpleName()); }
}
}
Which annotation is a composed annotation that specifically maps HTTP GET requests to a handler method in a `@Controller`?
What is the error in this Spring Boot application configuration regarding the bean's lifecycle method?
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import jakarta.annotation.PostConstruct;
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
class MyService {
@PostConstruct
public static void init() { // @PostConstruct methods cannot be static
System.out.println("MyService initialized.");
}
}
When using Spring Security with Thymeleaf forms, what is the typical mechanism used to automatically include a CSRF token in a form to protect against Cross-Site Request Forgery attacks?
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.Arrays;
public class SecureService {
@PreAuthorize("hasAnyRole('ADMIN', 'MANAGER')")
public String getManagementReport() { return "Management Report"; }
}
public class TestRunner {
public static void main(String[] args) {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("john", "pass", Arrays.asList(new SimpleGrantedAuthority("ROLE_MANAGER")))
);
SecureService service = new SecureService();
try { System.out.println(service.getManagementReport()); }
catch (Exception e) { System.out.println(e.getClass().getSimpleName()); }
}
}
What is the output of this code when a GET request is made to '/config'?
java
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class ConfigController {
@RequestMapping("/config")
public Map<String, Object> getConfig() {
Map<String, Object> config = new HashMap<>();
config.put("version", "1.0");
config.put("active", true);
return config;
}
}
What is the value printed by the `System.out.println` statement?
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
@Component class CounterComponent {
private int count = 0;
public void increment() { count++; }
public int getCount() { return count; }
}
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
var context = SpringApplication.run(DemoApplication.class, args);
var c1 = context.getBean(CounterComponent.class);
c1.increment();
var c2 = context.getBean(CounterComponent.class);
c2.increment();
System.out.println(c1.getCount());
}
}
What is the primary purpose of the `@Bean` annotation in a Spring `@Configuration` class?
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("UPDATE Product p SET p.price = :newPrice WHERE p.id = :id")
int updateProductPriceJPQL(@Param("newPrice") double newPrice, @Param("id") Long id);
}
// Assume ProductRepository is autowired as 'productRepository'
// And the database contains: Product(id=1, name='Headphones', price=100.00)
int updatedCount = productRepository.updateProductPriceJPQL(120.00, 1L);
System.out.println(updatedCount);
What is the output of this code when the `main` method of `MyApplication` is executed?
java
// src/main/java/com/example/app/MyApplication.java
package com.example.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
// src/main/java/com/example/other/MyComponent.java
package com.example.other;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
class MyComponent {
@PostConstruct
public void init() {
System.out.println("MyComponent Initialized");
}
}