![]() |
VOOZH | about |
Spring is one of the most popular frameworks for building enterprise applications in Java. It is an open-source, lightweight framework that allows developers to build simple, reliable, and scalable applications. Spring focuses on providing various ways to manage business objects efficiently.
It simplifies the development of web applications compared to classic Java frameworks and APIs like Java Database Connectivity (JDBC), JavaServer Pages (JSP), and Java Servlet. Spring uses advanced techniques such as Aspect-Oriented Programming (AOP), Plain Old Java Object (POJO), and Dependency Injection (DI) to develop robust enterprise applications.
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program.
In this article, we will focus on the @Component annotation in Springwith an example.
@Component is a class-level annotation used to mark a class as a Spring-managed bean. When Spring scans the application, it detects classes annotated with @Component and registers them as beans in the Spring IoC (Inversion of Control) container. These beans can then be injected into other components using dependency injection.
@Component is a generic stereotype annotation. Spring also provides more specialized annotations for specific use cases:
All these annotations (@Service, @Repository, @Controller) are specializations of @Component, meaning they inherit its functionality but provide additional semantics for specific roles.
Note: 'org.springframework.stereotype' and part of 'spring-context jar' supports all the annotations mentioned above.
Let’s create a simple Spring Boot application to demonstrate the use of the @Component annotation. In this example, we will create a basic Spring Boot application and see how Spring autodetects the component using annotation-based configuration and classpath scanning.
Use Spring Initializr to create a Spring Boot project with the following dependency:
Go to the src > main > java > your package name > right-click > New > Java Class and create your component class and mark it with @Component annotation. This class will be automatically detected and registered as a Spring Bean.
ComponentDemo.java:
In the main application class, we will use the CommandLineRunner interface to execute the demoFunction method when the application starts.
DemoApplication.java:
Output:
When you run the application, Spring Boot will automatically:
So you can see the power of @Component annotation, we didn’t have to do anything to inject our component to spring context. The below image shows the directory structure of our Spring Component example project.