๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Spring @Component Annotation


Introduction

  • @Component annotation was introduced in Spring 2.5, which is used for "Annotation-based Configuration" and offering an alternative to XML configuration.
  • It is a stereotype annotation used to denote a class as a Spring-managed component (bean). It tells the Spring container to instantiate the class and register it as a bean.

  • Syntax :
    The syntax of @Component is straightforward. It is placed above a class definition:
    import org.springframework.stereotype.Component;
    
    @Component
    public class Student
    {
        // Bean logic goes here
    }
    NOTE : By default, the bean name will be the class name with the first letter lowercased (student in this case).
  • We can also specify a custom bean name by providing a value as below :
    @Component("stdObj1")
    public class Student
    {
        // Bean logic goes here
    }

  • NOTE : When using @Component annotation in Spring, we have to use "@ComponentScan" annotation to detect and register @Component-annotated classes as beans.

  • Click Here for @Component Annotation Program.

  • @Component is the base stereotype for three specialized annotations :-
    1. @Controller : It is used in Spring MVC to indicate a controller.
    2. @Service : It indicates a service layer bean.
    3. @Repository : It is used for data access beans.

  • Hierarchy of @Component Annotation :-

    Component Annotation Hierarchy by Deepak Sir Smart Programming