When building applications with Spring, you will probably need to efficiently configure and manage components.
This is where @Component
annotation comes into play.
In this tutorial, you will learn about component annotation in Spring in detail, including its definition, usage, and importance in your application’s architecture.
By the end of this guide, you will be able to effectively utilize component annotation while creating Spring applications.
What is @Component Annotation in Spring?
@Component
annotation is a way to mark a class as a Spring component. You can think of it as a label that tells Spring,
Hey, this class is important, and I want you to manage it.
By annotating a class with @Component
, you are telling Spring that this class is a candidate for auto-detection when using component scanning.
Component scanning is a mechanism in Spring that allows you to automatically detect and register beans in your application context.
When you use @Component
on a class, Spring will automatically detect it and create a bean definition for it.
This means you don’t need to explicitly define the bean in your XML configuration file or use a BeanFactory
to register it.
@Component Annotation Example
Here’s an example of a simple class annotated with @Component
@Component public class MyService { // Your service implementation goes here }
In this example, the MyService
class is marked as a Spring component using the @Component
annotation. When Spring’s component scanning mechanism kicks in, it will detect this class and create a bean definition for it.
You can also use the @Component
annotation on classes that implement interfaces or extend abstract classes. For example,
@Component public class MyServiceImpl implements MyServiceInterface { // Your service implementation }
In this case, the MyServiceImpl
class is registered as a bean that implements the MyServiceInterface
interface.
Component Scanning
In Spring, component scanning is a process that allows you to automatically detect and register beans in the application context.
This process is enabled by using the @ComponentScan
annotation on your configuration classes.
When you use component annotation on a class, you are imperatively telling Spring that this class is a candidate for auto-detection.
Spring’s component scanning mechanism will then scan the classpath for classes annotated with @Component
or its stereotypes (@Service
, @Repository
, etc.) and register them as beans in the application context.
For example, let’s say you have a service class annotated with @Service
@Service public class MyService { // service implementation }
In your configuration class, you would use @ComponentScan
to enable component scanning
@Configuration @ComponentScan(basePackages = "com.codippa") public class AppConfig { // configuration classes }
In this example, Spring will scan the com.codippa
package and its sub-packages for classes annotated with @Component
or its stereotypes, and register them as beans in the application context.
This means that MyService
class will be automatically detected and registered as a bean, making it available for injection into other components.
@Component vs @Bean Annotation in Spring
Two of the most commonly used annotations in Spring are @Component
and @Bean.
While both annotations are used to register beans in the Spring IoC container, they serve different purposes and have distinct use cases.
When you use the @Component
annotation, you are telling Spring that this class is a candidate for autodetection when using annotation-based configuration and classpath scanning.
In other words, @Component
is a stereotype annotation that marks a class as a Spring component, which can then be auto-detected by Spring’s component scanning mechanism.
On the other hand, @Bean
annotation is used to explicitly declare a single bean, rather than letting Spring autodetect it.
When you use @Bean
, you are creating a bean definition in the Spring IoC container, which can then be injected into other components that require it.
Here’s an example of using the @Component
annotation, which is already covered above.
@Component public class MyService { // Service implementation }
In this example, MyService
class is marked as a Spring component, which can then be auto-detected by Spring’s component scanning mechanism.
Now, let’s take a look at an example of using the @Bean
annotation
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyService(); } }
In this example, myService()
method is annotated with @Bean
, which creates a bean definition in the Spring IoC container.
So, when should you use @Component
and when should you use @Bean
?
The general rule of thumb is to use @Component
for classes that are part of your application’s business logic, and use @Bean
for infrastructure beans or third-party libraries that need to be wired into your application.
Below is comparison of @Component
vs @Bean
annotations
Component Annotation (@Component) | Bean Annotation (@Bean) |
---|---|
Marks a class as a Spring component, making it eligible for auto-detection and registration in the application context. | Defines a single bean instance, which is registered in the application context. |
Typically used for classes that you write, such as service classes, repositories, or controllers. | Often used for third-party classes or when you need fine-grained control over bean creation. |
Enables component scanning, which allows Spring to automatically detect and register components. | Does not enable component scanning; beans must be explicitly defined and registered. |
Can be used in conjunction with other annotations, such as @Service, @Repository, or @Controller. | Typically used as a standalone annotation. |
@Component Annotation in Spring MVC
In a Spring MVC application, you may observe a method for configuring components that is more structured compared to other Spring-based applications.
This is because Spring MVC relies on a “context hierarchy” concept, where a main application context is created alongside one or more child contexts for each DispatcherServlet.
In a Spring MVC application, you’ll often have multiple components that need to be registered with the application context.
This is where the @Component
annotation becomes useful.
By annotating your components with @Component
`, you’re telling Spring to automatically detect and register them with the application context.
For example, let’s say you have a simple service class that you want to use in your Spring MVC application
@Component public class MyController { public void doSomething() { // implementation } }
In your Spring MVC configuration file (e.g. `mvc-config.xml`), you would then enable component scanning using the context:component-scan
element.
This tells Spring to scan the com.codippa.mvc
package and its sub-packages for any components annotated with @Component
.
If you are not using xml configuration but only annotation based configuration, then use @ComponentScan on configuration class as below
@Configuration @ComponentScan(basePackages = "com.codippa.mvc") public class AppConfig { // configuration logic here }
Once detected, these components will be registered with the application context and can be injected into other components using dependency injection.
@Component Annotation on abstract classes
When you annotate an abstract class with @Component
, Spring will not create a bean instance for that class.
Instead, it will only scan for concrete subclasses that extend the abstract class and create a bean of implementation class ONLY if it is annotated with @Component
.
If there is no class that extends an abstract class annotated with @Component
in the application, you will NOT get any error.
Let’s say you have an abstract class AbstractDAO
that provides a basic implementation of a data access object (DAO) for your application
@Component public abstract class AbstractDAO { @Autowired private JdbcTemplate jdbcTemplate; public List findAll() { // implementation } public T findById(Long id) { // implementation } }
In this example, AbstractDAO
class is annotated with @Component
, indicating that it’s a Spring component.
However, since it’s an abstract class, Spring won’t create a bean instance of it.
Now, let’s say you have a concrete component UserDAO
that extends AbstractDAO
@Component public class UserDAO extends AbstractDAO { public List findAllUsers() { return findAll(); } public User findUserById(Long id) { return findById(id); } }
In this case, Spring will create a bean instance of UserDAO
, and since it extends from AbstractDAO
, it will inherit the common behavior and properties defined in the abstract class.
@Component Annotation on interfaces
When you annotate an interface, Spring will not create a bean instance for that interface.
However, if you annotate an implementation class, Spring will create a bean instance for that class.
When you annotate an interface with @Component
, you are marking it as a candidate for autodetection by the Spring container.
This means that any implementation of that interface will also be considered a component, and Spring will automatically detect and register it.
Example,
@Component public interface MyService { void doSomething(); } @Service public class MyServiceImpl implements MyService { @Override public void doSomething() { // implementation details } }
In this example, MyService
interface is annotated with @Component
, making it a component. MyServiceImpl
class, which implements MyService
, is also annotated with @Service
, which is a stereotype annotation that implies @Component
.
As a result, Spring will detect and register both the interface and the implementation as components.
Conslusion
In this article, we saw how @Component
annotation enables Spring to automatically detect and register beans, making code more concise and efficient.