Bird
0
0

Which of the following is the correct way to declare a Spring component class?

easy📝 Syntax Q12 of 15
Spring Boot - Inversion of Control and Dependency Injection
Which of the following is the correct way to declare a Spring component class?
A@Component public class MyService {}
B@Service public void MyService() {}
Cpublic class MyService {}
D@Component void MyService() {}
Step-by-Step Solution
Solution:
  1. Step 1: Check annotation placement and class declaration

    The @Component annotation must be placed above a class declaration, like @Component public class MyService {}.
  2. Step 2: Identify incorrect syntax

    A plain public class misses the annotation, annotating a method with @Service or @Component is invalid since components must be classes.
  3. Final Answer:

    @Component public class MyService {} -> Option A
  4. Quick Check:

    Annotation + class declaration = correct syntax [OK]
Quick Trick: Always put @Component above a class, not a method [OK]
Common Mistakes:
  • Annotating methods instead of classes
  • Missing the annotation entirely
  • Using wrong annotations for components

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes