Bird
0
0

How can you ensure a Spring component annotated with @Component is only registered when the 'test' profile is active?

hard📝 Application Q8 of 15
Spring Boot - Inversion of Control and Dependency Injection
How can you ensure a Spring component annotated with @Component is only registered when the 'test' profile is active?
AAdd <code>@ConditionalOnProperty("test")</code> to the class.
BUse <code>@Component("test")</code> to specify the profile.
CSet <code>spring.profiles.active=test</code> in the component class.
DAnnotate the class with <code>@Profile("test")</code> alongside <code>@Component</code>.
Step-by-Step Solution
Solution:
  1. Step 1: Use @Profile annotation

    The @Profile annotation restricts bean registration to specified profiles.
  2. Step 2: Combine with @Component

    Annotate the class with both @Component and @Profile("test") to activate only in 'test' profile.
  3. Step 3: Other options incorrect

    @Component("test") sets bean name, not profile; spring.profiles.active is a property, not annotation; @ConditionalOnProperty checks properties, not profiles.
  4. Final Answer:

    Annotate the class with @Profile("test") alongside @Component. -> Option D
  5. Quick Check:

    Does @Profile control bean activation by profile? Yes [OK]
Quick Trick: Use @Profile with @Component for profile-specific beans [OK]
Common Mistakes:
  • Confusing bean name with profile
  • Trying to set profile via @Component parameter
  • Using property-based conditions instead of @Profile

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes