Subjects

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

What is the difference between @Component, @Service, @Repository, and @Controller? @Component, @Service, @Repository और @Controller में क्या अंतर है?

Answer

All four are stereotype annotations built on top of @Component, so all are detected by component scanning and registered as beans — functionally, Spring treats them the same way for the purpose of bean registration. The distinction is semantic and enables extra framework behavior for each layer.

@Repository additionally enables automatic translation of persistence-related exceptions into Spring's unified DataAccessException hierarchy. @Service marks business/service-layer logic (behaves like plain @Component, mainly documentation-level distinction). @Controller marks a Spring MVC web controller that returns view names, and @RestController (which combines @Controller + @ResponseBody) marks a REST endpoint. Using the correct stereotype communicates architectural intent and unlocks layer-specific tooling like AOP pointcuts targeting @Service classes.

@Repository public interface UserRepository extends JpaRepository<User, Long> {}
@Service public class UserService { }
@RestController public class UserController { }

चारों @Component के ऊपर बने स्टीरियोटाइप एनोटेशन हैं, इसलिए सभी कंपोनेंट स्कैनिंग द्वारा पहचाने जाते हैं और बीन्स के रूप में रजिस्टर होते हैं। अंतर सिमेंटिक है और हर लेयर के लिए अतिरिक्त फ्रेमवर्क व्यवहार सक्षम करता है।

@Repository अतिरिक्त रूप से पर्सिस्टेंस-संबंधित एक्सेप्शन को स्प्रिंग के एकीकृत DataAccessException पदानुक्रम में स्वचालित रूप से बदलने में सक्षम बनाता है। @Service बिज़नेस/सर्विस-लेयर लॉजिक को चिह्नित करता है। @Controller एक स्प्रिंग MVC वेब कंट्रोलर को चिह्नित करता है जो व्यू नाम रिटर्न करता है, और @RestController REST एंडपॉइंट को चिह्नित करता है।

@Repository public interface UserRepository extends JpaRepository<User, Long> {}
@Service public class UserService { }
@RestController public class UserController { }

Was this answer clear?