Bird
0
0

Which of the following is the correct way to declare a bean in a Spring Boot application using annotations?

easy📝 Syntax Q12 of 15
Spring Boot - Inversion of Control and Dependency Injection
Which of the following is the correct way to declare a bean in a Spring Boot application using annotations?
A@Autowired public MyService myService;
B@Service public void myService() {}
C@ComponentScan public class MyService {}
D@Bean public MyService myService() { return new MyService(); }
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct bean declaration syntax

    The @Bean annotation on a method returning an object is the standard way to declare a bean.
  2. Step 2: Check other options for correctness

    @Service is a class-level annotation, not for methods; @ComponentScan is for scanning packages; @Autowired injects beans, not declares them.
  3. Final Answer:

    @Bean public MyService myService() { return new MyService(); } -> Option D
  4. Quick Check:

    @Bean method declares bean [OK]
Quick Trick: Use @Bean on methods returning objects [OK]
Common Mistakes:
  • Using @Service on methods instead of classes
  • Confusing @ComponentScan with bean declaration
  • Using @Autowired to declare beans

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes