1. Overview
In this tutorial, weβll take a comprehensive look at the Spring @Component annotation and related areas. Weβll see the different ways we can integrate with some core Spring functionality and how to take advantage of its many benefits.
Further reading:
Spring Bean Annotations
Spring Web Annotations
2. Spring ApplicationContext
Before we can understand the value of @Component, we first need to understand a little bit about the Spring ApplicationContext.
Spring ApplicationContext is where Spring holds instances of objects that it has identified to be managed and distributed automatically. These are called beans.
Some of Springβs main features are bean management and the opportunity for dependency injection.
Using the Inversion of Control principle, Spring collects bean instances from our application and uses them at the appropriate time. We can show bean dependencies to Spring without handling the setup and instantiation of those objects.
The ability to use annotations like @Autowired to inject Spring-managed beans into our application is a driving force for creating powerful and scalable code in Spring.
So, how do we tell Spring about the beans we want it to manage for us? We should take advantage of Springβs automatic bean detection by using stereotype annotations in our classes.
3. @Component
@Component is an annotation that allows Spring to detect our custom beans automatically.
In other words, without having to write any explicit code, Spring will:
- Scan our application for classes annotated with @Component
- Instantiate them and inject any specified dependencies into them
- Inject them wherever needed
However, most developers prefer to use more specialized stereotype annotations to serve this function.
3.1. Spring Stereotype Annotations
Spring has provided a few specialized stereotype annotations: @Controller, @Service and @Repository. They all provide the same function as @Component.
They all act the same because they are all composed annotations with @Component as a meta-annotation for each of them. They are like @Component aliases with specialized uses and meaning outside Spring auto-detection or dependency injection.
We could theoretically use @Component exclusively for our bean auto-detection needs if we wanted to. On the flip side, we could also compose our specialized annotations that use @Component.
However, other areas of Spring look specifically for Springβs specialized annotations to provide additional automation benefits. So, we should probably stick with using the established specializations most of the time.
Letβs assume we have an example of each of these cases in our Spring Boot project:
@Controller
public class ControllerExample {
}
@Service
public class ServiceExample {
}
@Repository
public class RepositoryExample {
}
@Component
public class ComponentExample {
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface CustomComponent {
}
@CustomComponent
public class CustomComponentExample {
}
We could write a test that proves that each one is auto-detected by Spring and added to the ApplicationContext:
@SpringBootTest
@ExtendWith(SpringExtension.class)
public class ComponentUnitTest {
@Autowired
private ApplicationContext applicationContext;
@Test
public void givenInScopeComponents_whenSearchingInApplicationContext_thenFindThem() {
assertNotNull(applicationContext.getBean(ControllerExample.class));
assertNotNull(applicationContext.getBean(ServiceExample.class));
assertNotNull(applicationContext.getBean(RepositoryExample.class));
assertNotNull(applicationContext.getBean(ComponentExample.class));
assertNotNull(applicationContext.getBean(CustomComponentExample.class));
}
}
3.2. @ComponentScan
Before we rely entirely on @Component, we must understand that itβs only a plain annotation. The annotation serves the purpose of differentiating beans from other objects, such as domain objects.
However, Spring uses the @ComponentScan annotation to gather them into its ApplicationContext.
If weβre writing a Spring Boot application, it is helpful to know that @SpringBootApplication is a composed annotation that includes @ComponentScan. As long as our @SpringBootApplication class is at the root of our project, it will scan every @Component we define by default.
But in case our @SpringBootApplication class canβt be at the root of our project or we want to scan outside sources, we can configure @ComponentScan explicitly to look in whatever package we specify, as long as it exists on the classpath.
Letβs define an out-of-scope @Component bean:
package com.baeldung.component.scannedscope;
@Component
public class ScannedScopeExample {
}
Next, we can include it via explicit instructions to our @ComponentScan annotation:
package com.baeldung.component.inscope;
@SpringBootApplication
@ComponentScan({"com.baeldung.component.inscope", "com.baeldung.component.scannedscope"})
public class ComponentApplication {
//public static void main(String[] args) {...}
}
Finally, we can test that it exists:
@Test
public void givenScannedScopeComponent_whenSearchingInApplicationContext_thenFindIt() {
assertNotNull(applicationContext.getBean(ScannedScopeExample.class));
}
This is more likely to happen when we want to scan for an outside dependency included in our project.
3.3. @Component Limitations
There are some scenarios where we want a specific object to become a Spring-managed bean when we canβt use @Component.
Letβs define an object annotated with @Component in a package outside of our project:
package com.baeldung.component.outsidescope;
@Component
public class OutsideScopeExample {
}
Here is a test that proves that the ApplicationContext does not include the outside component:
@Test
public void givenOutsideScopeComponent_whenSearchingInApplicationContext_thenFail() {
assertThrows(NoSuchBeanDefinitionException.class, () -> applicationContext.getBean(OutsideScopeExample.class));
}
Also, we may not have access to the source code because it comes from a third-party source, and weβre unable to add the @Component annotation. Or perhaps we want to conditionally use one bean implementation over another, depending on the environment weβre running in. Auto-detection is usually sufficient, but when itβs not, we can use @Bean.
4. @Component vs @Bean
@Bean is also an annotation that Spring uses to gather beans at runtime, but itβs not used at the class level. Instead, we annotate methods with @Bean so that Spring can store the methodβs result as a Spring bean.
Weβll first create a POJO that has no annotations:
public class BeanExample {
}
Inside our class annotated with @Configuration, we can create a bean-generating method:
@Bean
public BeanExample beanExample() {
return new BeanExample();
}
BeanExample might represent a local class, or it might be an external class. It doesnβt matter because we need to return an instance of it.
We can then write a test that verifies Spring did pick up the bean:
@Test
public void givenBeanComponents_whenSearchingInApplicationContext_thenFindThem() {
assertNotNull(applicationContext.getBean(BeanExample.class));
}
We should note some important implications because of the differences between @Component and @Bean.
- @Component is a class-level annotation, but @Bean is at the method level, so @Component is only an option when a classβs source code is editable. @Bean can always be used, but itβs more verbose.
- @Component is compatible with Springβs auto-detection, but @Bean requires manual class instantiation.
- Using @Bean, decouples the instantiation of the bean from its class definition. This is why we can use it to make third-party classes into Spring beans. It also means we can introduce logic to decide which of several possible instance options for a bean to use.
5. Conclusion
Weβve just explored the Spring @Component annotation and other relevant topics. First, we discussed the various Spring stereotype annotations, which are just specialized versions of @Component.
Then we learned that @Component doesnβt do anything unless @ComponentScan can find it.
Finally, since itβs not possible to use @Component on classes because we donβt have the source code, we learned how to use the @Bean annotation instead.
