Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is @Bean vs @Component — when do you use each? @Bean बनाम @Component — प्रत्येक का उपयोग कब करें?

Answer

@Component (and its stereotypes like @Service) is a class-level annotation used when you own the source code — Spring detects the annotated class during component scanning and registers it as a bean automatically.

@Bean is a method-level annotation used inside a @Configuration class, giving explicit, programmatic control over how a bean is constructed — essential for registering beans from third-party libraries you don't own and can't annotate, for beans that need custom construction logic, or for conditionally creating beans based on properties or profiles.

@Configuration
public class AppConfig {
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.setConnectTimeout(Duration.ofSeconds(5)).build();
    }
}

@Component एक क्लास-लेवल एनोटेशन है जिसका उपयोग तब होता है जब आप सोर्स कोड के मालिक हों — स्प्रिंग कंपोनेंट स्कैनिंग के दौरान एनोटेटेड क्लास को पहचानता है और इसे स्वचालित रूप से बीन के रूप में रजिस्टर करता है।

@Bean एक मेथड-लेवल एनोटेशन है जिसका उपयोग @Configuration क्लास के अंदर होता है, जो बीन बनाने के तरीके पर स्पष्ट, प्रोग्रामेटिक नियंत्रण देता है — थर्ड-पार्टी लाइब्रेरीज़ के लिए ज़रूरी जिन्हें आप एनोटेट नहीं कर सकते।

@Configuration
public class AppConfig {
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.setConnectTimeout(Duration.ofSeconds(5)).build();
    }
}

Was this answer clear?