Spring Boot Annotations MCQs Annotations Interview java MCQ Spring Spring Boot Spring Boot 3 by devs5003 - May 7, 2025May 16, 20250 Last Updated on May 16th, 2025Spring Boot Annotations MCQs Understanding annotations in Spring Boot is essential for any Java developer working on enterprise-grade applications. These annotations simplify configuration, reduce boilerplate code, and help in building robust applications faster. Whether you’re preparing for technical interviews, certification exams, or just aiming to solidify your Spring Boot foundation, mastering Spring Boot annotations is non-negotiable. Need to revise annotations first? Read “Spring Boot Annotations Guide.” In this article, we will explore a set of Spring Boot Annotations MCQsย that cover: Concept-based questions to test your theoretical knowledge Code-based questions to check your practical understanding Scenario-based questions to simulate real-world use cases Each question is carefully created with detailed explanations and covers both correct and incorrect options to help you learn and revise effectively. So, letโs explore the world of Spring Boot Annotations MCQsย and test how well you know the framework that powers modern Java applications! Table of Contents Toggle Why Spring Boot Annotations Matter?Spring Boot Annotations MCQs (With Explanations) Why Spring Boot Annotations Matter? 90% of Java job interviews test your understanding of Spring Boot annotations. These MCQs coverย concept-based,ย code-based, andย scenario-based questions, just like real technical screenings. Bookmark this page. We update questions regularly! Spring Boot Annotations MCQs (With Explanations) Q#1. In order to bindย app.datasource.urlย fromย application.ymlย to a field, you would use: A)ย @Value("${app.datasource.url}") B)ย @ConfigurationProperties(prefix="app.datasource") C)ย @PropertySource("classpath:application.yml") D)ย @Autowired DataSource dataSource Answer:ย B Explanation: Bย is correct for hierarchical binding.ย Aย works for single properties,ย Cย loads files,ย Dย injects a datasource bean. Q#2. Consider the below code snippet. What does this code perform? @Configuration public class AppConfig { @Bean(name = "dataSource") public DataSource ds1() { return new HikariDataSource(); } @Primary @Bean public DataSource ds2() { return new TomcatDataSource(); } } @Service public class MyService { @Autowired private DataSource dataSource; } A)ย Injectsย HikariDataSource B)ย Injectsย TomcatDataSource C)ย Throwsย NoUniqueBeanDefinitionException D)ย None of the above Answer:ย B Explanation: Bย is correct.ย @Primaryย beatsย nameย inย @Autowiredย resolution. Q#3.ย Which annotationย cannotย be used at the class level? A)ย @Transactional B)ย @RequestMapping C)ย @Autowired D)ย @Profile Answer:ย C Explanation: Cย is correct.ย @Autowiredย is field/method/constructor-only. Others work at class level. Q#4. Consider the following code snippet: @Component public class Engine {} @Component public class Car { @Autowired private Engine engine; } Spring is not injecting the Engine bean into Car. What could be a valid reason? (A) The Engine class is abstract(B) The Car class was created using new instead of letting Spring manage it(C) The Engine class is not marked with @Service(D) Spring Boot doesnโt support field injection Answer: B Explanation: Option B is correct. If you instantiate a bean using new, Spring doesn’t manage it and won’t inject dependencies. Option A is incorrect unless itโs actually abstract. Option C is irrelevant because @Component is sufficient. Option D is incorrect: field injection is supported, though not always recommended. Q#5.ย Which annotation restricts method access to users with “ADMIN” role? A)ย @PreAuthorize("hasRole('ADMIN')") B)ย @Secured("ROLE_ADMIN") C)ย @RolesAllowed("ADMIN") D)ย All of the above Answer:ย D Explanation: Dย is correct. All three annotations work (noteย ROLE_ย prefix inย @Secured). Please go through a separate article on Spring Boot 3 compatible all Spring Boot Security annotations with examples. Q#6. Which one is true about @Component, @Repository, and @Service? (A) All are functionally identical and only differ semantically(B) Only @Repository supports exception translation(C) Only @Component is used for component scanning(D) @Service and @Component are interchangeable, but @Repository isnโt Answer: A Explanation: Option A is correct. All three annotations mark classes as Spring-managed beans. Their main difference is semantic clarity and role-based distinction. Option B is partially true, but all are picked up during scanning. Option C is incorrect as others are also picked. Option D is misleading. Q#7. Consider the following method: @GetMapping("/users") public String getUsers() { ... } What is the equivalent traditional annotation? (A) @RequestMapping(value = "/users")(B) @RequestMapping(value = "/users", method = RequestMethod.GET)(C) @RequestMapping(method = RequestMethod.POST)(D) @RequestMapping(value = "/users", consumes = "application/json") Answer: B Explanation: Option B is correct. @GetMapping is a composed annotation equivalent to @RequestMapping with method = RequestMethod.GET. Option A lacks the method, so itโs broader. Option C is a POST request, not GET. Option D adds a consumes clause unnecessarily. Q#8. A method is annotated with @Scheduled(fixedRate = 5000). What does it mean? (A) The method runs once every 5 seconds after the previous one ends(B) The method runs at exactly every 5-second interval, regardless of execution time(C) The method runs only once(D) The method runs after 5 seconds and never again Answer: B Explanation: Option B is correct. fixedRate runs the method every 5 seconds from the start of the last invocation. Option A describes fixedDelay. Option C and D are incorrect; the method will run periodically. In order to know about complete details of scheduled, kindly visit a separate article on @Scheduled annotation with examples. Q#9. Sara wants to inject a value from application.properties into a field. Which annotation should he use? (A) @Inject(B) @Autowired(C) @Value(D) @PropertySource Answer: C Explanation: Option C is correct. @Value(“${property.name}”) is used to inject property values. Option A and B are for bean injection. Option D defines a properties file source but does not inject values. Q#10. You annotate a controller method with @PostMapping but do not specify the consumes attribute. What does Spring assume? (A) It defaults to application/json(B) It defaults to application/xml(C) It accepts any content type(D) It rejects all incoming requests Answer: C Explanation: Option C is correct. If consumes is not specified, Spring will match all content types by default. Option A and B are incorrect unless explicitly configured. Option D is incorrect because Spring doesnโt reject requests by default. Q#11. A Spring Boot application has the following methods: @Transactional(propagation = Propagation.REQUIRED) public void methodA() { methodB(); // Calls methodB internally } @Transactional(propagation = Propagation.REQUIRES_NEW) public void methodB() { // Database operation } Whenย methodA()ย is called, what happens if an exception occurs inย methodB()? A)ย Bothย methodAย andย methodBย transactions roll back due to the defaultย REQUIREDย propagation. B)ย Onlyย methodB's transaction rolls back, whileย methodA's transaction commits successfully. C)ย Both transactions commit becauseย REQUIRES_NEWย creates an independent context. D)ย Aย TransactionSuspensionNotSupportedExceptionย is thrown since Spring cannot pauseย methodA's transaction. Answer:ย B Explanation: B is correct. REQUIRES_NEWย suspendsย methodA’s transaction and starts aย new independent transactionย forย methodB. Ifย methodBย fails, only its transaction rolls back. The original transaction (methodA) continues and can commit. A: Incorrectly assumesย REQUIREDย forces a shared rollback (it doesnโt apply toย REQUIRES_NEW). C: Misrepresents atomicity, REQUIRES_NEW doesnโt suppress rollbacks. D: False. Spring canย suspend transactions forย REQUIRES_NEWย (uses thread-bound connection holders). โฅ You may go through a separate article on all about @Transactional annotation with examples. Q#12.ย Andrew has two beans of the same type in his Spring context. He wants to inject a specific one into a component. Which annotation should he use along with @Autowired? (A) @Primary(B) @Qualifier(C) @Value(D) @Bean Answer: B Explanation: Option B is correct. @Qualifier is used to resolve the ambiguity when multiple beans of the same type exist. Option A can be used to mark a default bean, but it doesn’t allow specifying a bean at the injection point. Option C is used for injecting literal values. Option D defines a bean, not injects one. Q#13.ย Kevin used @Autowired for injecting a bean, but Spring throws NoSuchBeanDefinitionException. What could be a valid reason? (A) Bean was not annotated with @Component, @Service, or similar(B) Bean class is abstract(C) Bean is in an unscanned package(D) All of the above Answer: D Explanation: Option D is correct. All options are valid causes. If a class is not annotated or not in a scanned package, it wonโt be registered. Spring also cannot instantiate abstract classes, which leads to the error. Q#14.ย You annotated a class with both @Component and @Configuration. What will be the behavior in Spring Boot? (A) The class will only act as a configuration class(B) The class will act as a bean and configuration provider(C) Spring will throw a conflict error(D) Only the last annotation will take effect Answer: B Explanation: Option B is correct. @Configuration is itself a @Component, meaning the class is scanned as a bean and also used for defining additional beans via @Bean methods. There is no conflict, so Option C and D are incorrect. Option A is partially true but incomplete compared to B. Q#15.ย In a Spring Boot application, which annotation is used to enable component scanning and auto-configuration? (A) @EnableAutoConfiguration(B) @ComponentScan(C) @SpringBootApplication(D) @Configuration Answer: C Explanation: Option C is correct. The @SpringBootApplication annotation is a convenience annotation that combines @Configuration, @EnableAutoConfiguration, and @ComponentScan. Option A enables auto-configuration but doesn’t include component scanning. Option B enables component scanning but doesn’t include auto-configuration. Option D indicates a configuration class but doesn’t enable component scanning or auto-configuration. Q#16.ย Sachin is defining a REST endpoint using @RequestMapping(value = “/user”, method = RequestMethod.GET). Which annotation provides the same behavior more concisely? (A) @GetMapping("/user")(B) @RequestMapping("/user")(C) @RequestParam("/user")(D) @PathVariable("/user") Answer: A Explanation: Option A is correct. @GetMapping(“/user”) is a concise replacement for @RequestMapping(value = “/user”, method = RequestMethod.GET). Option B is valid but defaults to any HTTP method. Options C and D are used to extract request parameters and path variables, respectively, and are incorrect here. Q#17.ย You have created a Spring controller with @Controller and returned a plain string from a method. However, the string is interpreted as a view name instead of returning as a response body. Which annotation should you add to fix this? (A) @RestController(B) @ResponseBody(C) @RequestBody(D) Either A or B Answer: D Explanation: Option D is correct. @RestController is a shortcut for @Controller + @ResponseBody, and @ResponseBody alone can be used on the method to fix the issue. Option A is valid but applies at the class level. Option B is correct for the method. Option C, @RequestBody, is for reading the request body and is incorrect here. Q#18.ย James is loading external configuration from a YAML file in his Spring Boot application. Which annotation helps register external property resources? (A) @PropertySource(B) @ConfigurationProperties(C) @ImportResource(D) @EnableConfiguration Answer: A Explanation: Option A is correct. @PropertySource allows loading properties from external files. Option B binds external configuration to a bean but does not load the source. Option C imports XML-based configuration, and Option D is not a valid Spring annotation. Q#19.ย Mary wants to restrict access to a method so that it is only executed after successful authentication. Which annotation should she use? (A) @Secured(B) @PreAuthorize(C) @RolesAllowed(D) @SecurityFilter Answer: B Explanation: Option B is correct. @PreAuthorize provides expression-based access control before method execution. Option A, @Secured, is a simpler alternative and less flexible. Option C is part of JSR-250 and supported if enabled. Option D is not a valid Spring annotation. Q#20.ย Tom is working on a Spring Boot web application and wants to apply a global exception handler. Which annotation should be used on the class? (A) @ControllerAdvice(B) @RestControllerAdvice(C) @ExceptionHandler(D) @ErrorHandler Answer: A Explanation: Option A is correct. @ControllerAdvice is used for global exception handling across controllers. @ControllerAdviceย orย @RestControllerAdvice offers us to apply exception handlers to more than one or all controllers in our application. Option B is similar but specialized for REST APIs. Option C is used at the method level within exception handling classes. Option D is not a valid Spring annotation. In order to learn about Spring Boot Exception Handling in detail, kindly visit our article How To Handle Exceptions & Errors In Spring Boot?. Q#21.ย If you want to enable JPA repositories in your Spring Boot application. Which annotation should you use on a configuration class? (A) @EnableJpaRepositories(B) @EnableRepositories(C) @EnableJPA(D) @EnableEntityManager Answer: A Explanation: Option A is correct. The @EnableJpaRepositories annotation activates Spring Data JPA repositories. Option B is not a valid Spring annotation. Option C and D do not exist in Spring and will result in configuration errors. Q#22.ย Which annotation is used to define a method that returns a bean to be managed by the Spring container? (A) @Component(B) @Bean(C) @Service(D) @Repository Answer: B Explanation: Option B is correct. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context. Option A, @Component, is used to annotate classes, not methods. Option C, @Service, and Option D, @Repository, are also class-level annotations and not used for methods. Q#23. Robert is working on a controller and wants to map both /home and /dashboard URLs to the same method. Which option should he use? (A) @GetMapping({"/home", "/dashboard"})(B) @GetMapping("/home", "/dashboard")(C) @RequestMapping("/home", "/dashboard")(D) @RequestMapping(paths = {"/home", "/dashboard"}) Answer: A Explanation: Option A is correct. @GetMapping accepts an array of paths. Option B is incorrect syntax. Option C does not specify the method and has incorrect syntax. Option D uses a non-existent paths attribute, that makes it invalid. Q#24.ย You want to provide a default value if the property ‘app.port’ is missing. Which of the following is correct? (A) @Value("app.port:8080")(B) @Value("${app.port|8080}")(C) @Value("${app.port:8080}")(D) @Value("#{app.port ?: 8080}") Answer: C Explanation: Option C is correct. This syntax provides a fallback value using Spring Expression Language. Options A and B are syntactically invalid. Option D uses SpEL, but is not the common way for default values. Q#25.ย Which statements about @Bean are correct?ย (Multi-select) (A) Methods annotated with @Bean are invoked once per context load(B) @Bean methods can have parameters which Spring auto-wires(C) A bean defined this way must have a @Component annotation(D) @Bean can be used outside of @Configuration classes Answer: A, B, D Explanation: Options A, B, and D are correct. @Bean methods are called once and parameters are auto-injected. Option C is incorrect. @Bean doesnโt require @Component because the method itself defines the bean. Q#26. Consider the following code: @Value("${nonexistent.property}") private String config; What happens if the property is missing? (A) Spring throws an error during startup(B) Field gets empty string(C) The application runs without error(D) The property is ignored silently Answer: A Explanation: Option A is correct. Without a default fallback, missing properties injected using @Value will cause a startup failure. Option B and D are incorrect unless a fallback is specified. Q#27. How is dependency injection resolved with @Autowired? (A) By type(B) By name(C) By constructor only(D) By bean ID Answer: A Explanation: Option A is correct. @Autowired primarily resolves dependencies by type. If multiple candidates exist, qualifiers may be needed. Options B, C, and D are less typical or incorrect for @Autowired. Q#28.ย Which of the following best describes the difference between @Autowired and @Value? (A) @Autowired injects beans, @Value injects values(B) @Autowired is faster(C) @Value only works on classes(D) @Autowired can inject primitives Answer: A Explanation: Option A is correct. @Autowired is used to inject Spring-managed beans. @Value is for injecting external values (strings, numbers, etc.). Options B, C, and D are incorrect or misleading. Q#29.ย In which of the following scenarios is @Bean preferred over @Component? (A) When you have third-party classes without annotations(B) When using constructor injection(C) When defining services(D) When defining configuration classes Answer: A Explanation: Option A is correct. @Bean is useful for manually registering third-party or legacy classes that can’t be annotated. Options B and C are unrelated or better suited to @Component/@Service. Q#30. Which statements about @Configuration are correct?ย (A) It allows defining Spring beans using Java(B) It supports method-level @Bean declarations(C) It replaces the need for XML-based configuration(D) It is required for component scanning Answer: A, B, C Explanation: Options A, B, and C are correct. @Configuration is a Java-based alternative to XML config and supports bean definitions. Option D is false. Component scanning is handled by @ComponentScan. Q#31.ย A developer is using both @Configuration and @Bean in a class. Which of the following behaviors are enabled by this setup? (Multi-select) A) Registering custom beans in the Spring container B) Automatically mapping REST endpoints C) Creating reusable service objects manually D) Replacing auto-configuration defaults Answer: A, C, D Explanation: This pattern allows defining manual beans, useful when auto-configuration is insufficient or needs overrides. REST mapping (B) is unrelated. Q#31.ย Which of the following statements are true about the @Autowired annotation? (Multi-select) A) It can be used on constructors, fields, and setters. B) It allows manual bean registration in the Spring context. C) It tells Spring to resolve and inject a collaborating bean automatically. D) It can only be used on fields. Answer: A, C Explanation: @Autowired can be applied to constructors, fields, and setter methods to auto-wire beans. It directs Spring to resolve the dependency automatically. Option B is incorrect (manual registration is done via @Bean). Option D is incorrect because it’s not limited to fields. Q#32.ย Which annotations can be used to inject dependencies into a Spring bean? (Multi-select) A) @Autowired B) @Value C) @Bean D) @Inject Answer: A, D Explanation: @Autowired and @Inject (from JSR-330) can be used for dependency injection. @Value injects literals or expressions. @Bean is used to define beans, not inject them. Q#33.ย Which of the following can be declared in a class marked with @Configuration? (Multi-select) A) @Bean methods B) @RestController methods C) Configuration logic using Java D) Auto-wired properties Answer: A, C, D Explanation: A @Configuration class typically contains @Bean methods and can include Java logic and autowired dependencies. @RestController is unrelated to configuration classes. Q#34.ย A developer has multiple beans of the same type and wants to inject a specific one. Which of the following annotations can be used to achieve this? (Multi-select) A) @QualifierB) @PrimaryC) @Autowired(required=false)D) @Configuration Answer: A, B Explanation: @Qualifier helps specify the exact bean to inject, and @Primary marks one bean as the default when multiple candidates exist. Option C handles optional injection, not specificity. Option D is unrelated. Q#35.ย You want to define a bean only if a certain condition is met (e.g., a class is on the classpath). Which annotation combination would you use in Spring? A) @Bean with @ConditionalB) @Autowired with @QualifierC) @RestController with @RequestMappingD) @Configuration with @Value Answer: A Explanation: @Conditional is used with @Bean or @Configuration to define conditions under which a bean should be created. B, C, and D are not related to conditional bean creation. Q#36.ย In which situations would @Primary not be sufficient, requiring @Qualifier instead? (Multi-select) A) When multiple beans are candidates, and none is marked with @PrimaryB) When you need different beans injected in different placesC) When you only have one candidate beanD) When defining configuration classes Answer: A, B Explanation: @Primary sets a default, but @Qualifier is needed when different beans need to be injected in different contexts. C and D are unrelated. Q#37.ย Which annotations are part of Spring’s dependency injection and bean resolution mechanism? (Multi-select) A) @AutowiredB) @QualifierC) @PrimaryD) @RestControllerAdvice Answer: A, B, C Explanation: @Autowired is for injection, @Qualifier and @Primary are for resolving conflicts when multiple beans are available. @RestControllerAdvice is unrelated to dependency injection. Q#38.ย Can @Qualifier be used without @Autowired? A) No, it must be used with @AutowiredB) Yes, it can be used with @Inject or constructor injectionC) No, Spring doesn't allow thatD) Only inside configuration files Answer: B Explanation: Although often used with @Autowired, @Qualifier can also work with @Inject or constructor-based injection. Q#39.ย Which combination of annotations ensures fine-grained control over dependency injection with multiple beans? (Multi-select) A) @Autowired + @PrimaryB) @Autowired + @QualifierC) @Qualifier + @BeanD) @Component + @Primary Answers: A, B Explanation: Using @Autowired with @Primary or @Qualifier helps resolve conflicts when multiple beans exist. C and D are unrelated or incomplete without injection context. If you want to explore further on these core annotations,ย check out the official Spring annotations documentation. Q#40.ย What can @RestControllerAdvice be used for in Spring Boot? A) Exception HandlingB) Custom Request BindingC) Bean DiscoveryD) Applying Advice to Controllers Answer: A, B, D Explanation: @RestControllerAdvice supports exception handling, request binding, and applying shared advice logic. It does not handle bean discovery. Q#41.ย To test only the web layer (not the full context), which annotation would you use? A)ย @SpringBootTest B)ย @DataJpaTest C)ย @WebMvcTest D)ย @Test Answer:ย C Explanation: Cย is correct.ย @WebMvcTest slices tests to web layer.ย Aย loads full context,ย Bย focuses on JPA,ย Dย is a generic JUnit annotation. “Prefer Reading on Medium? Different set of more questions on Spring Boot Annotations MCQs & Practice Test are also available on [Medium] for a streamlined reading experience. Check it out if youโd like to bookmark, highlight, or engage with the community there!” Related