T4 Spring boot wings 1
Spring Boot MCQ
1. Spring Boot Annotations MCQs
Annotations simplify development by reducing the need for configuration. The questions in this section revolve around various Spring Boot annotations and their usage in real-world applications.
### 1. **What is the purpose of `@SpringBootApplication` in a Spring Boot application?**
- A) It enables Spring Security.
- B) It marks the main class for auto-configuration, component scanning, and configuration properties.
- C) It disables embedded server.
- D) It configures Hibernate.
**Answer:** B) It marks the main class for auto-configuration, component scanning, and configuration properties.
### 2. **Which annotation is used to define a Spring-managed bean?**
- A) `@Component`
- B) `@Service`
- C) `@Bean`
- D) All of the above
**Answer:** D) All of the above
### 3. **Which annotation is used to inject dependencies in Spring Boot?**
- A) `@Autowired`
- B) `@Inject`
- C) `@Resource`
- D) All of the above
**Answer:** D) All of the above
### 4. **What is the role of `@RestController` in Spring Boot?**
- A) It returns view templates for web applications.
- B) It is used to define a Spring MVC controller and handle RESTful web requests.
- C) It is used for defining configuration properties.
- D) It enables cross-origin requests.
**Answer:** B) It is used to define a Spring MVC controller and handle RESTful web requests.
### 5. **Which annotation is used to map HTTP requests to handler methods in Spring Boot?**
- A) `@RequestMapping`
- B) `@GetMapping`
- C) `@PostMapping`
- D) All of the above
**Answer:** D) All of the above
### 6. **What does the `@Entity` annotation signify in Spring Boot?**
- A) It is used to inject dependencies.
- B) It defines a class as a JPA entity.
- C) It sets up transaction management.
- D) It configures data validation.
**Answer:** B) It defines a class as a JPA entity.
### 7. **What is the purpose of `@EnableAutoConfiguration` in Spring Boot?**
- A) It automatically configures Spring applications based on dependencies present in the classpath.
- B) It enables database transaction management.
- C) It sets up security configurations.
- D) It allows manual configuration of beans.
**Answer:** A) It automatically configures Spring applications based on dependencies present in the classpath.
### 8. **What does the `@Repository` annotation indicate in Spring Boot?**
- A) It indicates that a class defines a JPA entity.
- B) It is used to mark a class as a Data Access Object (DAO) and makes it eligible for exception translation.
- C) It is used to mark classes for auto-wiring.
- D) It configures security for repositories.
**Answer:** B) It is used to mark a class as a Data Access Object (DAO) and makes it eligible for exception translation.
### 9. **Which annotation is used to create a custom configuration class in Spring Boot?**
- A) `@Configuration`
- B) `@Service`
- C) `@Component`
- D) `@RestController`
**Answer:** A) `@Configuration`
### 10. **Which annotation is used to map a specific path variable in a Spring Boot controller?**
- A) `@RequestParam`
- B) `@RequestBody`
- C) `@PathVariable`
- D) `@ModelAttribute`
**Answer:** C) `@PathVariable`
### 11. **Which annotation is used to bind HTTP request parameters to a method in Spring Boot?**
- A) `@RequestParam`
- B) `@RequestBody`
- C) `@PathVariable`
- D) `@ModelAttribute`
**Answer:** A) `@RequestParam`
### 12. **In Spring Boot, which annotation enables CORS on a method or class level?**
- A) `@EnableCors`
- B) `@AllowCors`
- C) `@CrossOrigin`
- D) `@CorsMapping`
**Answer:** C) `@CrossOrigin`
### 13. **Which annotation is used to bind form data to a Java object?**
- A) `@RequestBody`
- B) `@ModelAttribute`
- C) `@RequestParam`
- D) `@PathVariable`
**Answer:** B) `@ModelAttribute`
### 14. **What does `@Transactional` annotation do in Spring Boot?**
- A) It handles transactions automatically.
- B) It triggers exception handling.
- C) It maps HTTP requests to controllers.
- D) It manages the entity lifecycle.
**Answer:** A) It handles transactions automatically.
### 15. **Which annotation is used to create a scheduled task in Spring Boot?**
- A) `@Scheduled`
- B) `@Timer`
- C) `@Cron`
- D) `@Task`
**Answer:** A) `@Scheduled`
### 16. **What is the purpose of the `@Profile` annotation?**
- A) It defines security profiles for users.
- B) It defines different configurations for different environments (e.g., dev, prod).
- C) It is used for multi-tenancy.
- D) It profiles HTTP requests.
**Answer:** B) It defines different configurations for different environments (e.g., dev, prod).
### 17. **What does the `@Bean` annotation do?**
- A) It marks a method as a Spring Bean provider.
- B) It defines a Spring MVC controller.
- C) It auto-wires beans.
- D) It handles transaction management.
**Answer:** A) It marks a method as a Spring Bean provider.
### 18. **Which annotation is used to validate inputs in Spring Boot?**
- A) `@Valid`
- B) `@Validation`
- C) `@Validator`
- D) `@Validated`
**Answer:** A) `@Valid`
### 19. **Which annotation enables asynchronous method execution in Spring Boot?**
- A) `@Async`
- B) `@Scheduled`
- C) `@Asynchronous`
- D) `@FutureTask`
**Answer:** A) `@Async`
### 20. **In Spring Boot, which annotation is used to map a DTO object to a request body?**
- A) `@RequestBody`
- B) `@ResponseBody`
- C) `@ModelAttribute`
- D) `@RequestParam`
**Answer:** A) `@RequestBody`
### 21. **What is the role of `@EnableScheduling` in Spring Boot?**
- A) It enables scheduled tasks within the application.
- B) It enables task execution in multiple threads.
- C) It schedules email notifications.
- D) It controls database transactions.
**Answer:** A) It enables scheduled tasks within the application.
### 22. **Which annotation is used for exception handling in Spring Boot?**
- A) `@ExceptionHandler`
- B) `@RestControllerAdvice`
- C) `@ControllerAdvice`
- D) All of the above
**Answer:** D) All of the above
### 23. **What does the `@RequestBody` annotation do in Spring Boot?**
- A) It binds HTTP request body to a method parameter.
- B) It binds query parameters to a method parameter.
- C) It binds form data to method parameters.
- D) It serializes objects into JSON.
**Answer:** A) It binds HTTP request body to a method parameter.
### 24. **Which annotation is used to load properties into Spring Beans from a properties file?**
- A) `@PropertySource`
- B) `@ConfigurationProperties`
- C) `@Value`
- D) All of the above
**Answer:** D) All of the above
### 25. **What is the role of `@TestConfiguration` in Spring Boot tests?**
- A) It defines additional configurations for test cases.
- B) It enables auto-configuration.
- C) It configures REST endpoints for testing.
- D) It validates input data.
**Answer:** A) It defines additional configurations for test cases.
### 26. **Which annotation is used to enable Spring Data JPA repositories in Spring Boot?**
- A) `@EnableJpaRepositories`
- B) `@EnableRepositories`
- C) `@EnableDataRepositories`
- D) `@JpaRepository`
**Answer:** A) `@EnableJpaRepositories`
### 27. **What does `@RestControllerAdvice` do in Spring Boot?**
- A) It provides global exception handling for REST controllers.
- B) It maps REST endpoints.
- C) It schedules tasks.
- D) It enables transaction management.
**Answer:** A) It provides global exception handling for REST controllers.
### 28. **Which annotation is used to exclude specific beans from being auto-configured?**
- A) `@EnableAutoConfiguration`
- B) `@SpringBootApplication`
- C) `@ComponentScan`
- D) `@SpringBootApplication(exclude)`
**Answer:** D) `@SpringBootApplication(exclude)`
### 29. **What is the role of `@EnableWebSecurity`?**
- A) It enables Spring Security configuration.
- B) It disables security for specific endpoints.
- C) It enables security auto-configuration.
- D) It is used to secure databases.
**Answer:** A) It enables Spring Security configuration.
### 30. **Which annotation is used to inject values from the `application.properties` file?**
- A) `@Value`
- B) `@Inject`
- C) `@Autowired`
- D) `@Properties`
**Answer:** A) `@Value`
### 31. **Which annotation enables configuration of beans based on properties in Spring Boot?**
- A) `@PropertySource`
- B) `@ConfigurationProperties`
- C) `@Value`
- D) `@Profile`
**Answer:** B) `@ConfigurationProperties`
### 32. **What is the purpose of `@EnableTransactionManagement`?**
- A) It enables scheduling.
- B) It enables transaction management within the Spring application.
- C) It provides exception handling.
- D) It enables security features.
**Answer:** B) It enables transaction management within the Spring application.
### 33. **What does the `@Primary` annotation signify in Spring Boot?**
- A) It declares the main Spring Boot application class.
- B) It indicates the primary bean to be injected when multiple beans of the same type exist.
- C) It indicates the main configuration class.
- D) It denotes the first scheduled task in a queue.
**Answer:** B) It indicates the primary bean to be injected when multiple beans of the same type exist.
### 34. **Which annotation is used to cache results in Spring Boot?**
- A) `@EnableCaching`
- B) `@Cacheable`
- C) `@CachePut`
- D) All of the above
**Answer:** D) All of the above
### 35. **Which annotation allows configuring Cross-Origin Resource Sharing (CORS) globally?**
- A) `@CrossOrigin`
- B) `@EnableGlobalMethodSecurity`
- C) `@EnableCors`
- D) `@CorsMapping`
**Answer:** A) `@CrossOrigin`
### 36. **What is the role of `@ControllerAdvice` in Spring Boot?**
- A) It provides centralized exception handling for all controllers.
- B) It schedules tasks for controllers.
- C) It handles security for controllers.
- D) It configures transaction management.
**Answer:** A) It provides centralized exception handling for all controllers.
### 37. **What does the `@ConditionalOnMissingBean` annotation do?**
- A) It marks a bean as optional in the application context.
- B) It registers a bean only if a bean of the same type is not already present in the context.
- C) It loads bean conditionally based on the environment.
- D) It skips bean registration if a condition is met.
**Answer:** B) It registers a bean only if a bean of the same type is not already present in the context.
### 38. **Which annotation is used to enable method-level security in Spring Boot?**
- A) `@Secured`
- B) `@PreAuthorize`
- C) `@EnableGlobalMethodSecurity`
- D) `@AuthorizeRequests`
**Answer:** C) `@EnableGlobalMethodSecurity`
### 39. **What does `@PreAuthorize` annotation do?**
- A) It secures a method by evaluating a SpEL expression before execution.
- B) It secures REST endpoints only.
- C) It enables transaction management.
- D) It validates method parameters.
**Answer:** A) It secures a method by evaluating a SpEL expression before execution.
### 40. **Which annotation is used for unit testing in Spring Boot?**
- A) `@SpringBootTest`
- B) `@WebMvcTest`
- C) `@MockBean`
- D) All of the above
**Answer:** D) All of the above
### 41. **What does `@MockBean` do in Spring Boot testing?**
- A) It mocks a bean to use in tests.
- B) It injects a mock HTTP request.
- C) It creates a dummy database.
- D) It sets up test transactions.
**Answer:** A) It mocks a bean to use in tests.
### 42. **Which annotation is used to autowire beans in Spring Boot?**
- A) `@Autowired`
- B) `@Inject`
- C) `@Resource`
- D) All of the above
**Answer:** D) All of the above
### 43. **Which annotation is used to test only the web layer of the application in Spring Boot?**
- A) `@WebMvcTest`
- B) `@SpringBootTest`
- C) `@Test`
- D) `@MockMvcTest`
**Answer:** A) `@WebMvcTest`
### 44. **What does `@ConditionalOnProperty` do in Spring Boot?**
- A) It skips bean loading if a property is missing.
- B) It loads a bean based on the value of a property.
- C) It skips method execution based on property value.
- D) It evaluates properties at runtime.
**Answer:** B) It loads a bean based on the value of a property.
### 45. **Which annotation is used for asynchronous event listeners?**
- A) `@EventListener`
- B) `@Async`
- C) `@EventAsync`
- D) `@AsyncListener`
**Answer:** A) `@EventListener`
### 46. **What does `@SpringBootTest` annotation do in Spring Boot?**
- A) It loads the full Spring context for integration tests.
- B) It tests only controllers.
- C) It skips auto-configuration.
- D) It performs unit testing.
**Answer:** A) It loads the full Spring context for integration tests.
### 47. **What does `@ConditionalOnClass` annotation do?**
- A) It loads beans only if the specified class is present in the classpath.
- B) It binds a class to the configuration properties.
- C) It autowires a class with dependencies.
- D) It sets up security conditions for a class.
**Answer:** A) It loads beans only if the specified class is present in the classpath.
### 48. **Which annotation is used to exclude beans from component scanning?**
- A) `@ComponentScan(exclude)`
- B) `@ExcludeFromScan`
- C) `@SkipScan`
- D) `@IgnoreComponent`
**Answer:** A) `@ComponentScan(exclude)`
### 49. **What is the role of `@PathVariable` in Spring Boot?**
- A) It binds a URI template variable to a method parameter.
- B) It binds a query parameter to a method.
- C) It validates input fields.
- D) It secures web methods.
**Answer:** A) It binds a URI template variable to a method parameter.
### 50. **Which annotation configures Spring Boot to scan for `@Entity` classes?**
- A) `@EntityScan`
- B) `@EnableJpaEntities`
- C) `@JpaScan`
- D) `@AutoEntityScan`
**Answer:** A) `@EntityScan`
#### **2. Spring Boot Microservices MCQs**
Microservices are a core architectural style in modern applications, and Spring Boot makes microservice development easier with components like Spring Cloud. The questions in this section focus on building, deploying, and managing microservices with Spring Boot.
### 1. **What is the main benefit of using microservices architecture?**
- A) Single monolithic deployment
- B) Scalability and flexibility in development
- C) Tight coupling between services
- D) Simplified deployment
**Answer:** B) Scalability and flexibility in development
### 2. **Which annotation is used to enable Spring Cloud's service discovery?**
- A) `@EnableDiscoveryClient`
- B) `@EnableEurekaClient`
- C) `@EnableFeignClients`
- D) `@EnableConfigServer`
**Answer:** A) `@EnableDiscoveryClient`
### 3. **What does the `@FeignClient` annotation do in Spring Boot microservices?**
- A) It marks a class as a REST client to call other services.
- B) It enables service registration.
- C) It configures HTTP request handling.
- D) It provides transaction management.
**Answer:** A) It marks a class as a REST client to call other services.
### 4. **Which component is responsible for routing requests to different microservices?**
- A) API Gateway
- B) Service Registry
- C) Config Server
- D) Circuit Breaker
**Answer:** A) API Gateway
### 5. **What is the purpose of the `@EnableZuulProxy` annotation?**
- A) It enables Zuul proxy for routing requests to microservices.
- B) It configures security for microservices.
- C) It enables Eureka client functionality.
- D) It provides configuration management.
**Answer:** A) It enables Zuul proxy for routing requests to microservices.
### 6. **Which annotation is used to define a service that can be registered with Eureka?**
- A) `@SpringBootApplication`
- B) `@EnableDiscoveryClient`
- C) `@Service`
- D) `@RestController`
**Answer:** B) `@EnableDiscoveryClient`
### 7. **What does the `@EnableConfigServer` annotation do?**
- A) It enables the Spring Cloud Config Server to manage configuration properties.
- B) It registers a microservice with Eureka.
- C) It enables Zuul proxy.
- D) It configures Feign clients.
**Answer:** A) It enables the Spring Cloud Config Server to manage configuration properties.
### 8. **Which Spring Cloud component provides load balancing across microservices?**
- A) Ribbon
- B) Zuul
- C) Eureka
- D) Config Server
**Answer:** A) Ribbon
### 9. **What is the role of Spring Cloud Sleuth in microservices architecture?**
- A) It provides distributed tracing for debugging and monitoring microservices.
- B) It enables service discovery.
- C) It handles API gateway routing.
- D) It manages service configurations.
**Answer:** A) It provides distributed tracing for debugging and monitoring microservices.
### 10. **Which annotation is used to define a service in a Spring Boot microservices application?**
- A) `@Service`
- B) `@Component`
- C) `@RestController`
- D) `@Controller`
**Answer:** A) `@Service`
### 11. **Which tool is commonly used for managing and scaling microservices in a Kubernetes environment?**
- A) Docker
- B) Jenkins
- C) Helm
- D) Kubernetes
**Answer:** D) Kubernetes
### 12. **What does the `@HystrixCommand` annotation do in Spring Boot microservices?**
- A) It provides a circuit breaker to handle failures and fallback methods.
- B) It configures service discovery.
- C) It enables distributed tracing.
- D) It handles service routing.
**Answer:** A) It provides a circuit breaker to handle failures and fallback methods.
### 13. **Which annotation is used to enable service registration and discovery with Eureka in a Spring Boot application?**
- A) `@EnableEurekaServer`
- B) `@EnableDiscoveryClient`
- C) `@EnableFeignClients`
- D) `@EnableConfigServer`
**Answer:** B) `@EnableDiscoveryClient`
### 14. **What is the primary role of Spring Cloud Config Server?**
- A) To provide a centralized configuration server for managing application properties.
- B) To handle service registration and discovery.
- C) To provide a load balancer for microservices.
- D) To route API requests to microservices.
**Answer:** A) To provide a centralized configuration server for managing application properties.
### 15. **What does the `@EnableCircuitBreaker` annotation do?**
- A) It enables Hystrix for circuit breaking and fault tolerance in microservices.
- B) It configures the Zuul proxy.
- C) It provides load balancing capabilities.
- D) It manages distributed tracing.
**Answer:** A) It enables Hystrix for circuit breaking and fault tolerance in microservices.
### 16. **Which annotation is used to create a RESTful API client with Feign in Spring Boot?**
- A) `@FeignClient`
- B) `@RestController`
- C) `@Service`
- D) `@Client`
**Answer:** A) `@FeignClient`
### 17. **What is the purpose of the `@EnableZuulProxy` annotation in a Spring Boot application?**
- A) It configures Zuul as an API gateway.
- B) It registers the application with Eureka.
- C) It enables configuration properties.
- D) It creates RESTful web services.
**Answer:** A) It configures Zuul as an API gateway.
### 18. **Which component in Spring Cloud handles distributed configuration?**
- A) Config Server
- B) Eureka Server
- C) Zuul
- D) Ribbon
**Answer:** A) Config Server
### 19. **What does the `@EnableHystrixDashboard` annotation do?**
- A) It enables the Hystrix Dashboard for monitoring and visualizing circuit breaker metrics.
- B) It configures distributed tracing.
- C) It enables service discovery.
- D) It provides API gateway functionality.
**Answer:** A) It enables the Hystrix Dashboard for monitoring and visualizing circuit breaker metrics.
### 20. **Which annotation is used to configure Feign clients in a Spring Boot application?**
- A) `@EnableFeignClients`
- B) `@FeignClient`
- C) `@EnableDiscoveryClient`
- D) `@EnableConfigServer`
**Answer:** A) `@EnableFeignClients`
---
### 21. **What is the role of Spring Cloud Gateway in a microservices architecture?**
- A) It provides a way to route and filter requests to different microservices.
- B) It handles service registration and discovery.
- C) It provides distributed tracing.
- D) It manages configuration properties.
**Answer:** A) It provides a way to route and filter requests to different microservices.
### 22. **Which annotation is used to create a Eureka server in a Spring Boot application?**
- A) `@EnableEurekaServer`
- B) `@EnableDiscoveryClient`
- C) `@EnableConfigServer`
- D) `@EnableZuulProxy`
**Answer:** A) `@EnableEurekaServer`
### 23. **What is the purpose of the `@RibbonClient` annotation?**
- A) It configures Ribbon for client-side load balancing.
- B) It creates a Feign client.
- C) It enables Hystrix for fault tolerance.
- D) It configures Zuul for API gateway functionality.
**Answer:** A) It configures Ribbon for client-side load balancing.
### 24. **Which annotation is used to mark a class as a configuration class in a Spring Boot microservices application?**
- A) `@Configuration`
- B) `@Service`
- C) `@RestController`
- D) `@Component`
**Answer:** A) `@Configuration`
### 25. **What is the purpose of the `@LoadBalanced` annotation in Spring Boot microservices?**
- A) It enables Ribbon load balancing for REST template.
- B) It configures Hystrix circuit breaker.
- C) It sets up a Zuul proxy.
- D) It registers a service with Eureka.
**Answer:** A) It enables Ribbon load balancing for REST template.
### 26. **Which tool is used for managing inter-service communication in a microservices architecture?**
- A) Feign
- B) Zuul
- C) Ribbon
- D) Config Server
**Answer:** A) Feign
### 27. **What does the `@EnableFeignClients` annotation enable in a Spring Boot application?**
- A) It enables Feign client support for RESTful service communication.
- B) It configures Zuul for routing.
- C) It enables Hystrix for fault tolerance.
- D) It registers services with Eureka.
**Answer:** A) It enables Feign client support for RESTful service communication.
### 28. **Which annotation is used to create a fallback method for Hystrix circuit breaker?**
- A) `@HystrixCommand`
- B) `@Fallback`
- C) `@Retry`
- D) `@CircuitBreaker`
**Answer:** A) `@HystrixCommand`
### 29. **What does the `@EnableDiscoveryClient` annotation do in a Spring Boot microservices application?**
- A) It registers the service with a service discovery server like Eureka.
- B) It configures Feign clients.
- C) It enables Zuul for routing.
- D) It sets up Ribbon for load balancing.
**Answer:** A) It registers the service with a service discovery server like Eureka.
### 30. **Which annotation is used to define a RESTful service endpoint in Spring Boot microservices?**
- A) `@RestController`
- B) `@Service`
- C) `@Component`
- D) `@Configuration`
**Answer:** A) `@RestController`
### 31. **What does the `@HystrixCollapser` annotation do?**
- A) It batches multiple requests into a single call to reduce latency.
- B) It creates a circuit breaker.
- C) It handles service discovery.
- D) It enables load balancing.
**Answer:** A) It batches multiple requests into a single call to reduce latency.
### 32. **What is the role of Spring Cloud Bus in microservices architecture?**
- A) It provides a way to propagate events and configuration changes across microservices.
- B) It handles load balancing.
- C) It manages service discovery.
- D) It routes API requests.
**Answer:** A) It provides a way to propagate events and configuration changes across microservices.
### 33. **Which annotation is used to enable distributed tracing in a Spring Boot application?**
- A) `@EnableZipkinServer`
- B) `@EnableSleuth`
- C) `@EnableTracing`
- D) `@EnableTrace`
**Answer:** B) `@EnableSleuth`
### 34. **What is the purpose of the `@EnableEurekaServer` annotation?**
- A) It sets up a Eureka server for service registration and discovery.
- B) It configures Hystrix for fault tolerance.
- C) It enables Feign clients.
- D) It creates a Zuul proxy.
**Answer:** A) It sets up a Eureka server for service registration and discovery.
### 35. **Which tool is used for API gateway functionality in a microservices architecture?**
- A) Zuul
- B) Ribbon
- C) Eureka
- D) Config Server
**Answer:** A) Zuul
### 36. **What does the `@EnableFeignClients` annotation provide in a Spring Boot application?**
- A) It enables Feign clients for RESTful service communication.
- B) It enables service discovery with Eureka.
- C) It configures Zuul for routing.
- D) It manages distributed tracing.
**Answer:** A) It enables Feign clients for RESTful service communication.
### 37. **Which annotation is used to create a client-side load balancer in a Spring Boot application?**
- A) `@RibbonClient`
- B) `@FeignClient`
- C) `@EnableDiscoveryClient`
- D) `@LoadBalanced`
**Answer:** A) `@RibbonClient`
### 38. **What is the purpose of the `@EnableHystrix` annotation?**
- A) It enables Hystrix for circuit breaking and fault tolerance.
- B) It sets up service discovery.
- C) It configures load balancing.
- D) It enables API gateway functionality.
**Answer:** A) It enables Hystrix for circuit breaking and fault tolerance.
### 39. **Which annotation is used to define a service that should be discovered by Eureka?**
- A) `@EnableDiscoveryClient`
- B) `@Service`
- C) `@Component`
- D) `@RestController`
**Answer:** A) `@EnableDiscoveryClient`
### 40. **What is the purpose of the `@LoadBalanced` annotation on a `RestTemplate` bean?**
- A) It enables client-side load balancing with Ribbon.
- B) It enables service discovery.
- C) It configures Hystrix circuit breaker.
- D) It creates a Feign client.
**Answer:** A) It enables client-side load balancing with Ribbon.
---
### 41. **Which annotation is used to create a Hystrix circuit breaker?**
- A) `@HystrixCommand`
- B) `@HystrixCircuitBreaker`
- C) `@CircuitBreaker`
- D) `@Fallback`
**Answer:** A) `@HystrixCommand`
### 42. **What does the `@EnableSleuth` annotation do?**
- A) It enables distributed tracing with Spring Cloud Sleuth.
- B) It sets up a Eureka server.
- C) It configures Feign clients.
- D) It creates a Zuul proxy.
**Answer:** A) It enables distributed tracing with Spring Cloud Sleuth.
### 43. **Which annotation is used to configure a Zuul API gateway in Spring Boot?**
- A) `@EnableZuulProxy`
- B) `@EnableZuulGateway`
- C) `@ZuulProxy`
- D) `@ZuulGateway`
**Answer:** A) `@EnableZuulProxy`
### 44. **What is the role of `@HystrixCollapser` in Spring Boot microservices?**
- A) It batches multiple requests into a single call to reduce latency.
- B) It provides fallback methods for circuit breakers.
- C) It manages service discovery.
- D) It configures Feign clients.
**Answer:** A) It batches multiple requests into a single call to reduce latency.
### 45. **Which annotation is used to mark a class as a Feign client in Spring Boot?**
- A) `@FeignClient`
- B) `@RestClient`
- C) `@HttpClient`
- D) `@ServiceClient`
**Answer:** A) `@FeignClient`
### 46. **What does the `@EnableConfigServer` annotation do?**
- A) It enables Spring Cloud Config Server to serve configuration properties.
- B) It configures Ribbon for load balancing.
- C) It creates a Zuul API gateway.
- D) It enables service discovery.
**Answer:** A) It enables Spring Cloud Config Server to serve configuration properties.
### 47. **Which annotation is used to configure an application to be a Eureka client?**
- A) `@EnableDiscoveryClient`
- B) `@EnableEurekaClient`
- C) `@EnableFeignClients`
- D) `@EnableConfigServer`
**Answer:** A) `@EnableDiscoveryClient`
### 48. **What does the `@FeignClient` annotation provide?**
- A) It creates a REST client that can communicate with other microservices.
- B) It sets up Zuul routing.
- C) It enables distributed tracing.
- D) It configures Ribbon for load balancing.
**Answer:** A) It creates a REST client that can communicate with other microservices.
### 49. **Which component in Spring Cloud helps manage application configuration properties?**
- A) Config Server
- B) Eureka Server
- C) Zuul
- D) Ribbon
**Answer:** A) Config Server
### 50. **What is the purpose of the `@CircuitBreaker` annotation?**
- A) It provides fault tolerance by managing failures and fallback methods.
- B) It enables service discovery.
- C) It configures load balancing.
- D) It handles API gateway functionality.
**Answer:** A) It provides fault tolerance by managing failures and fallback methods.
3. Spring Security MCQs
Security is a crucial part of any web application, and Spring Security provides an extensive set of tools for securing Spring Boot applications. This section covers authentication, authorization, and common security vulnerabilities in real-world applications.
1. **Which class is the central point of the Spring Security framework?**
- A) `AuthenticationManager`
- B) `SecurityContext`
- C) `SecurityContextHolder`
- D) `WebSecurityConfigurerAdapter`
**Answer:** C) `SecurityContextHolder`
2. **In Spring Security, which method is used to authenticate a user programmatically?**
- A) `SecurityContext.authenticate()`
- B) `AuthenticationManager.authenticate()`
- C) `SecurityContextHolder.getContext().authenticate()`
- D) `SecurityConfigurerAdapter.authenticate()`
**Answer:** B) `AuthenticationManager.authenticate()`
3. **Which filter is responsible for processing JWT tokens in Spring Security?**
- A) `UsernamePasswordAuthenticationFilter`
- B) `OncePerRequestFilter`
- C) `JwtAuthenticationFilter`
- D) `FilterSecurityInterceptor`
**Answer:** B) `OncePerRequestFilter`
4. **What is the primary role of `SecurityContextHolder` in Spring Security?**
- A) To store security-related information such as authentication details.
- B) To manage encryption keys.
- C) To handle logging of security events.
- D) To enforce CSRF protection.
**Answer:** A) To store security-related information such as authentication details.
5. **Which annotation is used to apply method-level security in a Spring Boot application?**
- A) `@PreAuthorize`
- B) `@Secured`
- C) `@RolesAllowed`
- D) All of the above
**Answer:** D) All of the above
6. **In real-world applications, how can you ensure that a user has a specific role before executing a method?**
- A) Using the `@Secured` annotation
- B) Using the `@PostAuthorize` annotation
- C) Using the `@PreAuthorize` annotation with SpEL
- D) Manually checking inside the method
**Answer:** C) Using the `@PreAuthorize` annotation with SpEL
7. **Which of the following is used to store authentication details after a user has logged in?**
- A) `HttpSession`
- B) `SecurityContextHolder`
- C) `SecurityFilterChain`
- D) `ThreadLocalStorage`
**Answer:** B) `SecurityContextHolder`
8. **In JWT-based authentication, where is the JWT token typically stored in an HTTP request?**
- A) Cookie
- B) Request Header
- C) URL Parameters
- D) Session
**Answer:** B) Request Header
9. **In a real-life Spring Boot eCommerce application, how would you restrict the checkout page to only authenticated users?**
- A) Add `@Secured("ROLE_USER")` annotation to the controller method
- B) Use `@PreAuthorize("hasRole('USER')")` annotation
- C) Manually check if the user is logged in
- D) Both A and B
**Answer:** D) Both A and B
10. **What is the default URL for the Spring Security login page?**
- A) `/login`
- B) `/signin`
- C) `/authenticate`
- D) `/userLogin`
**Answer:** A) `/login`
11. **Which of the following is a key benefit of using JWT for authentication in Spring Security?**
- A) Stateless Authentication
- B) Session-based Authentication
- C) Database Query Reduction
- D) Both A and C
**Answer:** D) Both A and C
12. **How do you enable CORS globally in a Spring Security application?**
- A) Using `@CrossOrigin` on controller methods
- B) Implementing a `CorsFilter`
- C) Overriding `WebSecurityConfigurerAdapter` and calling `cors()`
- D) Setting up a `FilterRegistrationBean`
**Answer:** C) Overriding `WebSecurityConfigurerAdapter` and calling `cors()`
13. **What is the purpose of CSRF protection in Spring Security?**
- A) To prevent Cross-Site Scripting (XSS) attacks
- B) To prevent unauthorized commands sent from a user that the web application trusts
- C) To prevent SQL injection attacks
- D) To protect the user’s session ID from theft
**Answer:** B) To prevent unauthorized commands sent from a user that the web application trusts
14. **In a real-world banking application, which Spring Security feature would you enable to protect against account takeovers?**
- A) CSRF protection
- B) Two-factor authentication
- C) JWT tokens
- D) Password encryption
**Answer:** B) Two-factor authentication
15. **Which of the following is NOT a valid `SecurityContext` storage strategy in Spring Security?**
- A) `MODE_GLOBAL`
- B) `MODE_INHERITABLETHREADLOCAL`
- C) `MODE_SESSION`
- D) `MODE_THREADLOCAL`
**Answer:** A) `MODE_GLOBAL`
16. **Which annotation is used in Spring Security to enable security at the method level for specific roles?**
- A) `@PostAuthorize`
- B) `@Secured`
- C) `@PreAuthorize`
- D) Both B and C
**Answer:** D) Both B and C
17. **In a real-life insurance application, which method would be best for restricting a claims page to users with a `ROLE_ADMIN`?**
- A) Use `@Secured("ROLE_ADMIN")`
- B) Use `@PreAuthorize("hasRole('ADMIN')")`
- C) Manually check user role inside the controller
- D) Both A and B
**Answer:** D) Both A and B
18. **In Spring Security, how do you configure different authentication mechanisms such as form login, HTTP Basic, and OAuth2 in a single application?**
- A) Using multiple `SecurityConfigurerAdapter` classes
- B) Overriding the `configure(HttpSecurity http)` method
- C) Configuring them in separate filter chains
- D) Adding them as method-level annotations
**Answer:** B) Overriding the `configure(HttpSecurity http)` method
19. **Which method is responsible for setting the `Authentication` object in the `SecurityContextHolder`?**
- A) `setAuthentication()`
- B) `authenticate()`
- C) `SecurityContextHolder.getContext().setAuthentication()`
- D) `AuthenticationManager.authenticate()`
**Answer:** C) `SecurityContextHolder.getContext().setAuthentication()`
20. **In JWT-based authentication, what is the typical response for a failed login attempt?**
- A) A new JWT token with limited access
- B) `403 Forbidden` HTTP response
- C) `401 Unauthorized` HTTP response
- D) `200 OK` with error message
**Answer:** C) `401 Unauthorized` HTTP response
21. **In a real-world microservices architecture, how can Spring Security be used to propagate authentication across different services?**
- A) Using shared session state
- B) By sharing the `SecurityContextHolder` between services
- C) By using JWT tokens passed between microservices
- D) Using OAuth2
**Answer:** C) By using JWT tokens passed between microservices
22. **What is the purpose of `@EnableGlobalMethodSecurity` in Spring Security?**
- A) To globally disable method security
- B) To enable method-level security annotations like `@Secured` and `@PreAuthorize`
- C) To restrict method calls to a specific user
- D) To enforce password policies
**Answer:** B) To enable method-level security annotations like `@Secured` and `@PreAuthorize`
23. **Which of the following security concerns is best addressed by OAuth2 in a Spring Security-based web application?**
- A) User authentication
- B) Password encryption
- C) Delegated authorization for third-party access
- D) Session management
**Answer:** C) Delegated authorization for third-party access
24. **In Spring Security, how can you restrict a resource to both `ROLE_ADMIN` and `ROLE_MANAGER`?**
- A) `@Secured({"ROLE_ADMIN", "ROLE_MANAGER"})`
- B) `@PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')")`
- C) `@RolesAllowed({"ROLE_ADMIN", "ROLE_MANAGER"})`
- D) Both A and B
**Answer:** D) Both A and B
25. **How does Spring Security prevent session fixation attacks?**
- A) By using HTTPS
- B) By generating a new session ID after successful authentication
- C) By using encrypted tokens
- D) By implementing CORS
**Answer:** B) By generating a new session ID after successful authentication
26. **In a Spring Security JWT-based authentication system, how would you handle token expiration in a real-world application?**
- A) Set a long expiration time for the token
- B) Generate a new token upon each request
- C) Use a refresh token mechanism
- D) Store the token in the database
**Answer:** C) Use a refresh token mechanism
27. **Which interface in Spring Security provides the current authenticated user's details?**
- A) `UserDetailsService`
- B) `AuthenticationProvider`
- C) `UserDetails`
- D) `Principal`
**Answer:** C) `UserDetails`
28. **Which method is used in Spring Security to retrieve the current authenticated user?**
- A) `SecurityContextHolder.getContext().getAuthentication()`
- B) `SecurityContext.getUser()`
- C) `SecurityUtils.getUser()`
- D) `AuthenticationManager.getCurrentUser()`
**Answer:** A) `SecurityContextHolder.getContext().getAuthentication()`
29. **In a real-world financial application, which Spring Security feature would you use to secure sensitive API endpoints like bank transfers?**
- A) OAuth2
- B) Method-level security using `@PreAuthorize`
- C) JWT Authentication
- D) All of the above
**Answer:** D) All of the above
30. **How can you implement custom authentication in Spring Security?**
- A) By extending the `AuthenticationProvider` class
- B) By using `UserDetailsService`
- C) By creating a custom `AuthenticationManager`
- D) Both A and B
**Answer:** D) Both A and B
31. **Which filter is typically used in Spring Security to handle form-based login?**
- A) `JwtAuthenticationFilter`
- B) `UsernamePasswordAuthenticationFilter`
- C) `OncePerRequestFilter`
- D) `BasicAuthenticationFilter`
**Answer:** B) `UsernamePasswordAuthenticationFilter`
32. **What is the purpose of `UserDetailsService` in Spring Security?**
- A) To store user credentials
- B) To load user-specific data during authentication
- C) To manage roles and permissions
- D) To handle security filters
**Answer:** B) To load user-specific data during authentication
33. **How would you prevent brute-force attacks on user login in a real-world Spring Security application?**
- A) Set a very strong password policy
- B) Lock the account after several failed login attempts
- C) Use two-factor authentication
- D) Both B and C
**Answer:** D) Both B and C
34. **Which class is used to configure HTTP Basic Authentication in Spring Security?**
- A) `HttpBasicConfigurer`
- B) `BasicAuthenticationFilter`
- C) `HttpSecurity`
- D) `WebSecurityConfigurerAdapter`
**Answer:** C) `HttpSecurity`
35. **What is the main purpose of `@EnableWebSecurity` in a Spring Boot application?**
- A) To enable global security
- B) To enable the Spring Security filter chain
- C) To apply security to web services
- D) To enable HTTP security
**Answer:** B) To enable the Spring Security filter chain
36. **In real-world e-commerce platforms, which of the following features would you implement to secure sensitive data such as user passwords?**
- A) Hashing and salting passwords
- B) JWT tokens for login
- C) CSRF protection
- D) Role-based access control
**Answer:** A) Hashing and salting passwords
37. **What is the role of `GrantedAuthority` in Spring Security?**
- A) To define the actions that a user is allowed to perform
- B) To store user credentials
- C) To hold security context data
- D) To configure web security
**Answer:** A) To define the actions that a user is allowed to perform
38. **Which class in Spring Security handles the logout functionality?**
- A) `LogoutFilter`
- B) `AuthenticationManager`
- C) `LogoutSuccessHandler`
- D) `SecurityContextHolder`
**Answer:** A) `LogoutFilter`
39. **In a real-world SaaS application, how would you ensure that only premium users can access specific features?**
- A) By using JWT claims to store user role
- B) By using method-level security annotations like `@PreAuthorize`
- C) By setting up roles in the database and checking them programmatically
- D) All of the above
**Answer:** D) All of the above
40. **How does Spring Security provide protection against Cross-Site Scripting (XSS) attacks?**
- A) By automatically escaping output in Thymeleaf templates
- B) By enabling CSRF tokens
- C) By applying content security policies
- D) By using JWT tokens
**Answer:** A) By automatically escaping output in Thymeleaf templates
41. **In a real-world banking application, which authentication mechanism would you recommend for customer logins?**
- A) HTTP Basic Authentication
- B) JWT tokens with two-factor authentication
- C) OAuth2 login with social accounts
- D) None of the above
**Answer:** B) JWT tokens with two-factor authentication
42. **What is the default behavior of Spring Security when CSRF protection is enabled?**
- A) It automatically generates a CSRF token for each session
- B) It requires every POST request to include the CSRF token
- C) It blocks all GET requests
- D) Both A and B
**Answer:** D) Both A and B
43. **In a real-life hospital management system, how would you restrict access to the patient's data?**
- A) By using role-based access control (RBAC)
- B) By encrypting sensitive data
- C) By applying method-level security using `@PreAuthorize`
- D) All of the above
**Answer:** D) All of the above
44. **What is `@AuthenticationPrincipal` used for in Spring Security?**
- A) To inject the current authenticated user into a method parameter
- B) To check if the current user is authenticated
- C) To define the authentication mechanism
- D) To log security events
**Answer:** A) To inject the current authenticated user into a method parameter
45. **Which exception is thrown when a user tries to access a secured resource without proper authentication?**
- A) `AccessDeniedException`
- B) `AuthenticationException`
- C) `UnauthorizedException`
- D) `AuthenticationCredentialsNotFoundException`
**Answer:** B) `AuthenticationException`
46. **In a real-life multi-tenant application, how would you differentiate security for different tenants?**
- A) Use tenant-specific roles in JWT tokens
- B) Use a custom security filter for each tenant
- C) Use method-level security with tenant-based conditions
- D) All of the above
**Answer:** D) All of the above
47. **Which method in `AuthenticationManager` is responsible for verifying the credentials of a user?**
- A) `authenticate()`
- B) `validate()`
- C) `checkCredentials()`
- D) `login()`
**Answer:** A) `authenticate()`
48. **In Spring Security, what is the purpose of `@PermitAll`?**
- A) To grant access to a specific resource to all authenticated users
- B) To allow access to a resource regardless of the user's authentication status
- C) To configure security for public APIs
- D) To permit all HTTP methods for a specific endpoint
**Answer:** B) To allow access to a resource regardless of the user's authentication status
49. **What is the primary use of `BCryptPasswordEncoder` in Spring Security?**
- A) To hash passwords using the bcrypt algorithm
- B) To decode JWT tokens
- C) To encrypt sensitive data
- D) To manage user roles
**Answer:** A) To hash passwords using the bcrypt algorithm
50. **Which class in Spring Security is responsible for handling exceptions such as authentication failures?**
- A) `AccessDeniedHandler`
- B) `AuthenticationFailureHandler`
- C) `ExceptionTranslationFilter`
- D) `AuthenticationManager`
**Answer:** C) `ExceptionTranslationFilter`
#### **4. Core Spring Boot MCQs**
Spring Boot simplifies the configuration process in Spring applications. This section includes questions about the core functionalities of Spring Boot, from configuration to running the application.
### 1. **What is the main purpose of Spring Boot?**
- A) To provide a ready-to-use framework for building web applications
- B) To simplify the configuration and deployment of Spring applications
- C) To provide advanced security features
- D) To enhance the performance of Java applications
**Answer:** B) To simplify the configuration and deployment of Spring applications
### 2. **Which annotation is used to mark a class as a Spring Boot application?**
- A) `@Component`
- B) `@Configuration`
- C) `@SpringBootApplication`
- D) `@EnableAutoConfiguration`
**Answer:** C) `@SpringBootApplication`
### 3. **What does the `@SpringBootApplication` annotation do?**
- A) Configures the application context
- B) Enables auto-configuration and component scanning
- C) Provides RESTful web service capabilities
- D) Configures a data source
**Answer:** B) Enables auto-configuration and component scanning
### 4. **Which annotation is used to enable Spring Boot's auto-configuration feature?**
- A) `@EnableAutoConfiguration`
- B) `@Configuration`
- C) `@ComponentScan`
- D) `@Service`
**Answer:** A) `@EnableAutoConfiguration`
### 5. **How do you specify a custom property in a Spring Boot application?**
- A) By using `application.properties` or `application.yml`
- B) By defining it in the `pom.xml`
- C) By using a custom configuration class
- D) By setting it in the `web.xml` file
**Answer:** A) By using `application.properties` or `application.yml`
### 6. **Which method is used to run a Spring Boot application?**
- A) `Application.run()`
- B) `SpringApplication.run()`
- C) `ApplicationContext.run()`
- D) `SpringBoot.run()`
**Answer:** B) `SpringApplication.run()`
### 7. **What is the default port number for a Spring Boot application?**
- A) 8080
- B) 9090
- C) 7070
- D) 6060
**Answer:** A) 8080
### 8. **Which Spring Boot annotation is used to create a RESTful web service?**
- A) `@RestController`
- B) `@Service`
- C) `@Controller`
- D) `@Component`
**Answer:** A) `@RestController`
### 9. **Which annotation is used to define a REST endpoint in Spring Boot?**
- A) `@RequestMapping`
- B) `@GetMapping`
- C) `@PostMapping`
- D) All of the above
**Answer:** D) All of the above
### 10. **How can you exclude specific auto-configurations in Spring Boot?**
- A) By using the `exclude` attribute in `@SpringBootApplication`
- B) By modifying `application.properties`
- C) By setting environment variables
- D) By using `@Configuration` classes
**Answer:** A) By using the `exclude` attribute in `@SpringBootApplication`
### 11. **Which annotation is used to mark a class as a configuration class in Spring Boot?**
- A) `@Configuration`
- B) `@Service`
- C) `@Component`
- D) `@Repository`
**Answer:** A) `@Configuration`
### 12. **What is the purpose of the `@Bean` annotation in Spring Boot?**
- A) To declare a bean in the Spring application context
- B) To mark a class as a Spring component
- C) To configure the application properties
- D) To handle RESTful requests
**Answer:** A) To declare a bean in the Spring application context
### 13. **Which annotation is used to automatically detect and register components in Spring Boot?**
- A) `@ComponentScan`
- B) `@EnableAutoConfiguration`
- C) `@Bean`
- D) `@Configuration`
**Answer:** A) `@ComponentScan`
### 14. **How do you handle exceptions globally in a Spring Boot application?**
- A) By using `@ControllerAdvice`
- B) By using `@ExceptionHandler`
- C) By defining exception handling in `application.properties`
- D) By implementing `ErrorController`
**Answer:** A) By using `@ControllerAdvice`
### 15. **What is the purpose of the `@Autowired` annotation?**
- A) To inject dependencies into a Spring-managed bean
- B) To declare a Spring component
- C) To define a RESTful endpoint
- D) To configure application settings
**Answer:** A) To inject dependencies into a Spring-managed bean
### 16. **Which annotation is used to create a RESTful API client in Spring Boot?**
- A) `@FeignClient`
- B) `@RestController`
- C) `@Service`
- D) `@Component`
**Answer:** A) `@FeignClient`
### 17. **How can you specify the profile of a Spring Boot application?**
- A) By setting the `spring.profiles.active` property in `application.properties`
- B) By using `@Profile` annotation
- C) By specifying profiles in `pom.xml`
- D) By defining profiles in the application code
**Answer:** A) By setting the `spring.profiles.active` property in `application.properties`
### 18. **Which annotation is used to define a Spring Boot REST controller?**
- A) `@RestController`
- B) `@Controller`
- C) `@Service`
- D) `@Component`
**Answer:** A) `@RestController`
### 19. **What is the purpose of the `application.properties` file in Spring Boot?**
- A) To define application-specific configuration properties
- B) To declare Spring beans
- C) To manage RESTful endpoints
- D) To handle exceptions globally
**Answer:** A) To define application-specific configuration properties
### 20. **How do you define a datasource in a Spring Boot application?**
- A) By setting properties in `application.properties`
- B) By using `@DataSource` annotation
- C) By creating a `DataSource` bean
- D) By defining it in the `pom.xml`
**Answer:** A) By setting properties in `application.properties`
### 21. **Which Spring Boot annotation is used to enable asynchronous processing?**
- A) `@EnableAsync`
- B) `@Async`
- C) `@EnableScheduling`
- D) `@Scheduled`
**Answer:** A) `@EnableAsync`
### 22. **What is the purpose of the `@Transactional` annotation in Spring Boot?**
- A) To manage database transactions
- B) To define a RESTful API
- C) To handle exception management
- D) To inject dependencies
**Answer:** A) To manage database transactions
### 23. **Which annotation is used to configure scheduling tasks in Spring Boot?**
- A) `@EnableScheduling`
- B) `@Scheduled`
- C) `@Async`
- D) `@Component`
**Answer:** A) `@EnableScheduling`
### 24. **What does the `@RequestMapping` annotation do?**
- A) Maps HTTP requests to handler methods
- B) Defines a Spring component
- C) Configures a RESTful client
- D) Handles database transactions
**Answer:** A) Maps HTTP requests to handler methods
### 25. **How can you customize the embedded servlet container in Spring Boot?**
- A) By configuring properties in `application.properties`
- B) By creating a `ServletWebServerFactory` bean
- C) By modifying the `web.xml` file
- D) By using `@Configuration` class
**Answer:** B) By creating a `ServletWebServerFactory` bean
### 26. **Which annotation is used to mark a class as a Spring-managed bean?**
- A) `@Component`
- B) `@Bean`
- C) `@Service`
- D) `@Controller`
**Answer:** A) `@Component`
### 27. **What is the purpose of the `@Value` annotation?**
- A) To inject property values into a Spring bean
- B) To define a REST endpoint
- C) To configure a data source
- D) To manage transaction boundaries
**Answer:** A) To inject property values into a Spring bean
### 28. **How do you enable Spring Boot's Actuator features?**
- A) By including the `spring-boot-starter-actuator` dependency
- B) By using the `@EnableActuator` annotation
- C) By configuring properties in `application.properties`
- D) By creating an `Actuator` bean
**Answer:** A) By including the `spring-boot-starter-actuator` dependency
### 29. **Which annotation is used to indicate a Spring Boot application's main class?**
- A) `@SpringBootApplication`
- B) `@Main`
- C) `@Application`
- D) `@BootApplication`
**Answer:** A) `@SpringBootApplication`
### 30. **What is the default location of the `application.properties` file in a Spring Boot project?**
- A) `src/main/resources`
- B) `src/main/java`
- C) `src/test/resources`
- D) `src/main/config`
**Answer:** A) `src/main/resources`
### 31. **How can you inject a list of beans into a Spring Boot application?**
- A) By using `@Autowired` on a `List` or `Set`
- B) By defining beans in `application.properties`
- C) By using `@Value` with a list
- D) By configuring beans in `web.xml`
**Answer:** A) By using `@Autowired` on a `List` or `Set`
### 32. **Which annotation is used to enable and configure embedded server support in Spring Boot?**
- A) `@SpringBootApplication`
- B) `@EnableAutoConfiguration`
- C) `@ComponentScan`
- D) `@Configuration`
**Answer:** A) `@SpringBootApplication`
### 33. **How do you define a custom initializer for a Spring Boot application?**
- A) By implementing `ApplicationContextInitializer`
- B) By using `@CustomInitializer`
- C) By defining it in `application.properties`
- D) By using `@PostConstruct`
**Answer:** A) By implementing `ApplicationContextInitializer`
### 34. **What is the purpose of the `@PostConstruct` annotation?**
- A) To specify a method to be executed after bean initialization
- B) To mark a method as an initialization method
- C) To configure scheduled tasks
- D) To define a RESTful endpoint
**Answer:** A) To specify a method to be executed after bean initialization
### 35. **Which dependency is required to enable Spring Boot's web capabilities?**
- A) `spring-boot-starter-web`
- B) `spring-boot-starter-data-jpa`
- C) `spring-boot-starter-security`
- D) `spring-boot-starter-actuator`
**Answer:** A) `spring-boot-starter-web`
### 36. **How do you define a bean with a specific name in Spring Boot?**
- A) By using `@Bean(name = "beanName")`
- B) By using `@Component("beanName")`
- C) By defining it in `application.properties`
- D) By using `@Service("beanName")`
**Answer:** A) By using `@Bean(name = "beanName")`
### 37. **What is the purpose of the `@ConditionalOnProperty` annotation?**
- A) To conditionally create a bean based on a property value
- B) To define a RESTful endpoint
- C) To enable component scanning
- D) To configure database transactions
**Answer:** A) To conditionally create a bean based on a property value
### 38. **Which Spring Boot annotation is used to handle RESTful web service responses?**
- A) `@ResponseBody`
- B) `@RequestMapping`
- C) `@RestController`
- D) `@Controller`
**Answer:** A) `@ResponseBody`
### 39. **How can you externalize configuration in a Spring Boot application?**
- A) By using environment variables
- B) By using `application.properties`
- C) By defining properties in the code
- D) By modifying `web.xml`
**Answer:** A) By using environment variables
### 40. **What is the default profile for a Spring Boot application?**
- A) `default`
- B) `prod`
- C) `test`
- D) `dev`
**Answer:** A) `default`
### 41. **Which Spring Boot annotation is used to schedule tasks?**
- A) `@Scheduled`
- B) `@TaskScheduler`
- C) `@EnableScheduling`
- D) `@Async`
**Answer:** A) `@Scheduled`
### 42. **What does the `@Service` annotation signify?**
- A) It marks a class as a service component in the business layer
- B) It defines a RESTful web service endpoint
- C) It configures a data source
- D) It handles exception management
**Answer:** A) It marks a class as a service component in the business layer
### 43. **How do you set up a Spring Boot application to connect to a database?**
- A) By including the appropriate starter dependency and configuring `application.properties`
- B) By using `@DatabaseConfig` annotation
- C) By setting up `data-source` in `web.xml`
- D) By defining a `DataSource` bean manually
**Answer:** A) By including the appropriate starter dependency and configuring `application.properties`
### 44. **Which Spring Boot annotation is used to enable Spring Data JPA repositories?**
- A) `@EnableJpaRepositories`
- B) `@EnableDataRepositories`
- C) `@JpaRepository`
- D) `@EnableRepositories`
**Answer:** A) `@EnableJpaRepositories`
### 45. **What is the purpose of the `@SpringBootTest` annotation?**
- A) To provide support for testing Spring Boot applications
- B) To define a Spring Boot application's main class
- C) To enable auto-configuration
- D) To configure database properties
**Answer:** A) To provide support for testing Spring Boot applications
### 46. **Which annotation is used to enable caching in a Spring Boot application?**
- A) `@EnableCaching`
- B) `@Cacheable`
- C) `@CacheConfig`
- D) `@Caching`
**Answer:** A) `@EnableCaching`
### 47. **How can you define custom properties in Spring Boot's `application.properties`?**
- A) By defining key-value pairs
- B) By using XML configuration
- C) By creating a `DataSource` bean
- D) By modifying `web.xml`
**Answer:** A) By defining key-value pairs
### 48. **What is the purpose of the `@Entity` annotation in Spring Boot?**
- A) To mark a class as a JPA entity
- B) To define a RESTful endpoint
- C) To handle database transactions
- D) To declare a Spring bean
**Answer:** A) To mark a class as a JPA entity
### 49. **How do you configure an embedded database in Spring Boot?**
- A) By including the appropriate starter dependency in `pom.xml`
- B) By configuring it in `application.properties`
- C) By defining a `DataSource` bean manually
- D) By using `@EmbeddedDatabase` annotation
**Answer:** A) By including the appropriate starter dependency in `pom.xml`
### 50. **Which annotation is used to define a configuration class in Spring Boot?**
- A) `@Configuration`
- B) `@Bean`
- C) `@Component`
- D) `@Service`
**Answer:** A) `@Configuration`
#### **5. Java MCQs for Spring Boot Developers**
Java is the backbone of Spring Boot, and understanding core Java concepts is essential for effective development. This section focuses on Java fundamentals and their application in Spring Boot.
### 1. **Which keyword is used to create a new object in Java?**
- A) `create`
- B) `new`
- C) `instantiate`
- D) `object`
**Answer:** B) `new`
### 2. **What is the default value of a boolean variable in Java?**
- A) `true`
- B) `false`
- C) `null`
- D) `0`
**Answer:** B) `false`
### 3. **Which method is used to compare two strings in Java for equality?**
- A) `compare()`
- B) `equals()`
- C) `==`
- D) `isEqual()`
**Answer:** B) `equals()`
### 4. **What is the purpose of the `final` keyword in Java?**
- A) To define a constant value
- B) To make a method non-overridable
- C) To prevent a class from being subclassed
- D) All of the above
**Answer:** D) All of the above
### 5. **Which collection class provides a key-value mapping in Java?**
- A) `ArrayList`
- B) `HashMap`
- C) `HashSet`
- D) `LinkedList`
**Answer:** B) `HashMap`
### 6. **What does the `transient` keyword indicate in Java?**
- A) A variable should not be serialized
- B) A variable is volatile
- C) A variable is immutable
- D) A variable is synchronized
**Answer:** A) A variable should not be serialized
### 7. **What is the default access level of a class member in Java?**
- A) `public`
- B) `private`
- C) `protected`
- D) Package-private
**Answer:** D) Package-private
### 8. **Which Java keyword is used to handle exceptions?**
- A) `try`
- B) `catch`
- C) `finally`
- D) All of the above
**Answer:** D) All of the above
### 9. **What is the purpose of the `super` keyword in Java?**
- A) To access the superclass's methods and constructors
- B) To create a superclass
- C) To override a superclass method
- D) To define a method in the superclass
**Answer:** A) To access the superclass's methods and constructors
### 10. **Which of the following is used to create a thread in Java?**
- A) Implementing `Runnable` interface
- B) Extending `Thread` class
- C) Both A and B
- D) Neither A nor B
**Answer:** C) Both A and B
---
### 11. **What does the `static` keyword indicate in Java?**
- A) A method or variable belongs to the class, rather than instances of the class
- B) A method is synchronized
- C) A variable is immutable
- D) A method is abstract
**Answer:** A) A method or variable belongs to the class, rather than instances of the class
### 12. **What is the purpose of the `this` keyword in Java?**
- A) To refer to the current instance of a class
- B) To create a new instance of a class
- C) To access static members
- D) To call a superclass's constructor
**Answer:** A) To refer to the current instance of a class
### 13. **Which exception type is not checked at compile-time?**
- A) `IOException`
- B) `SQLException`
- C) `RuntimeException`
- D) `ClassNotFoundException`
**Answer:** C) `RuntimeException`
### 14. **What is the purpose of the `abstract` keyword in Java?**
- A) To declare a class that cannot be instantiated
- B) To declare a method that must be implemented by subclasses
- C) To define an abstract data type
- D) Both A and B
**Answer:** D) Both A and B
### 15. **Which keyword is used to prevent a class from being subclassed in Java?**
- A) `final`
- B) `static`
- C) `abstract`
- D) `private`
**Answer:** A) `final`
### 16. **What is the purpose of the `interface` keyword in Java?**
- A) To define a contract that implementing classes must follow
- B) To provide a concrete implementation of a class
- C) To create a new instance of a class
- D) To define a method with a default implementation
**Answer:** A) To define a contract that implementing classes must follow
### 17. **Which collection class provides a synchronized version of `ArrayList`?**
- A) `Vector`
- B) `LinkedList`
- C) `CopyOnWriteArrayList`
- D) `ConcurrentLinkedQueue`
**Answer:** A) `Vector`
### 18. **What does the `volatile` keyword indicate in Java?**
- A) A variable's value may be changed by multiple threads
- B) A variable is immutable
- C) A variable is static
- D) A variable is transient
**Answer:** A) A variable's value may be changed by multiple threads
### 19. **Which of the following is true about constructors in Java?**
- A) A constructor can be private
- B) A constructor must have the same name as the class
- C) A constructor does not have a return type
- D) All of the above
**Answer:** D) All of the above
### 20. **What is the purpose of the `Enum` type in Java?**
- A) To define a set of named constants
- B) To create a new instance of a class
- C) To declare a variable as final
- D) To define an abstract class
**Answer:** A) To define a set of named constants
---
### 21. **Which Java feature allows multiple classes to be grouped under a single type?**
- A) Inheritance
- B) Polymorphism
- C) Abstraction
- D) Interfaces
**Answer:** D) Interfaces
### 22. **How do you declare a method that does not return any value in Java?**
- A) By using `void`
- B) By using `null`
- C) By using `empty`
- D) By not specifying a return type
**Answer:** A) By using `void`
### 23. **What is the purpose of the `default` keyword in an interface?**
- A) To provide a default implementation of a method
- B) To define a constant
- C) To create an abstract method
- D) To declare a private method
**Answer:** A) To provide a default implementation of a method
### 24. **Which of the following is a characteristic of a static nested class in Java?**
- A) It can access all static members of the outer class
- B) It can access non-static members of the outer class
- C) It is not associated with any instance of the outer class
- D) Both A and C
**Answer:** D) Both A and C
### 25. **What is the use of the `synchronized` keyword in Java?**
- A) To control access to resources by multiple threads
- B) To define a method that can be overridden
- C) To declare a method as abstract
- D) To handle exceptions
**Answer:** A) To control access to resources by multiple threads
### 26. **What does the `instanceof` operator do in Java?**
- A) Tests whether an object is an instance of a specific class or interface
- B) Creates a new instance of a class
- C) Checks if two objects are the same
- D) Defines a new class
**Answer:** A) Tests whether an object is an instance of a specific class or interface
### 27. **Which method is used to convert a string to an integer in Java?**
- A) `Integer.parseInt()`
- B) `String.toInteger()`
- C) `Integer.valueOf()`
- D) `String.parseInt()`
**Answer:** A) `Integer.parseInt()`
### 28. **What is the purpose of the `StringBuilder` class in Java?**
- A) To create and manipulate mutable strings
- B) To define immutable strings
- C) To perform string comparisons
-
D) To convert strings to other data types
**Answer:** A) To create and manipulate mutable strings
### 29. **Which of the following is true about the `hashCode()` method in Java?**
- A) It returns an integer hash code value for the object
- B) It must be overridden when `equals()` is overridden
- C) It is used to compare objects for equality
- D) Both A and B
**Answer:** D) Both A and B
### 30. **What does the `clone()` method do in Java?**
- A) Creates a copy of the object
- B) Clones a class definition
- C) Duplicates the method definition
- D) Creates a new instance of a class
**Answer:** A) Creates a copy of the object
---
### 31. **What is the purpose of the `Collection` interface in Java?**
- A) To define the core collection framework in Java
- B) To provide methods for creating collections
- C) To handle thread synchronization
- D) To define a set of mathematical operations
**Answer:** A) To define the core collection framework in Java
### 32. **Which of the following is not a direct subclass of `Exception` in Java?**
- A) `RuntimeException`
- B) `IOException`
- C) `Error`
- D) `SQLException`
**Answer:** C) `Error`
### 33. **How do you handle multiple exceptions in a single `catch` block in Java?**
- A) By using the `|` operator to separate exceptions
- B) By using nested `try-catch` blocks
- C) By defining multiple `catch` blocks
- D) By using the `throws` keyword
**Answer:** A) By using the `|` operator to separate exceptions
### 34. **What is the purpose of the `@Override` annotation in Java?**
- A) To indicate that a method is overriding a method in a superclass
- B) To define a method as abstract
- C) To create a new method in an interface
- D) To prevent method overriding
**Answer:** A) To indicate that a method is overriding a method in a superclass
### 35. **Which of the following collections implements the `Set` interface in Java?**
- A) `ArrayList`
- B) `HashSet`
- C) `LinkedList`
- D) `PriorityQueue`
**Answer:** B) `HashSet`
### 36. **How do you declare a generic method in Java?**
- A) By specifying type parameters in angle brackets before the return type
- B) By using the `generic` keyword
- C) By defining type parameters in method arguments
- D) By extending a generic class
**Answer:** A) By specifying type parameters in angle brackets before the return type
### 37. **Which method is used to get the length of an array in Java?**
- A) `length()`
- B) `size()`
- C) `getLength()`
- D) `length`
**Answer:** D) `length`
### 38. **What is the output of `3 + 4 + "5"` in Java?**
- A) `7`
- B) `34`
- C) `75`
- D) `12`
**Answer:** C) `75`
### 39. **Which interface in Java provides methods to iterate over a collection?**
- A) `Iterable`
- B) `Iterator`
- C) `Collection`
- D) `List`
**Answer:** B) `Iterator`
### 40. **What is the purpose of the `try-with-resources` statement in Java?**
- A) To automatically close resources like files and streams
- B) To handle exceptions without explicit `catch` blocks
- C) To create a new resource
- D) To define a method that handles resources
**Answer:** A) To automatically close resources like files and streams
---
### 41. **Which method in Java returns the class type of an object?**
- A) `getClass()`
- B) `classType()`
- C) `getType()`
- D) `typeOf()`
**Answer:** A) `getClass()`
### 42. **What is the purpose of the `super` keyword in a constructor?**
- A) To call a constructor from the superclass
- B) To create a new superclass
- C) To access static members of the superclass
- D) To override a method in the superclass
**Answer:** A) To call a constructor from the superclass
### 43. **Which Java class is used to represent date and time before Java 8?**
- A) `LocalDateTime`
- B) `Date`
- C) `Calendar`
- D) `Time`
**Answer:** B) `Date`
### 44. **What does the `assert` keyword do in Java?**
- A) Tests a boolean condition and throws an `AssertionError` if the condition is false
- B) Defines a constant value
- C) Creates a new instance of a class
- D) Checks if an object is null
**Answer:** A) Tests a boolean condition and throws an `AssertionError` if the condition is false
### 45. **Which of the following keywords is used to create an immutable class in Java?**
- A) `final`
- B) `static`
- C) `transient`
- D) `abstract`
**Answer:** A) `final`
### 46. **What does the `instanceof` operator check in Java?**
- A) Whether an object is an instance of a specific class or subclass
- B) Whether an object is null
- C) Whether two objects are the same
- D) Whether a variable is static
**Answer:** A) Whether an object is an instance of a specific class or subclass
### 47. **What is the purpose of the `default` method in interfaces in Java 8?**
- A) To provide a default implementation of a method
- B) To define a constant value
- C) To create an abstract method
- D) To override a method in a subclass
**Answer:** A) To provide a default implementation of a method
### 48. **Which class provides a way to handle concurrent collections in Java?**
- A) `ConcurrentHashMap`
- B) `HashMap`
- C) `TreeMap`
- D) `LinkedHashMap`
**Answer:** A) `ConcurrentHashMap`
### 49. **What is the purpose of the `volatile` keyword in Java?**
- A) To indicate that a variable's value may be changed by multiple threads
- B) To ensure a variable is constant
- C) To synchronize access to a variable
- D) To mark a method as final
**Answer:** A) To indicate that a variable's value may be changed by multiple threads
### 50. **Which method is used to start a thread in Java?**
- A) `start()`
- B) `run()`
- C) `execute()`
- D) `begin()`
**Answer:** A) `start()`
Comments
Post a Comment