In this quick article, we will discuss how to use @Component
annotation in Spring (Spring Boot)
based applications.
The @Component annotation indicates that an annotated class is a "component". Such classes are considered candidates for auto-detection when using annotation-based configuration and classpath scanning.
In short, @Component
is a class-level annotation. During the component scan,
Spring Framework
automatically
detects classes annotated with @Component
annotation and creates Spring
beans for those
classes.
Spring can automatically scan a package for beans if component scanning is enabled.
@ComponentScan configures which packages to scan for classes with annotation configuration. We can
specify
the base package names directly with one of the basePackages
or value
arguments (value is an alias for
basePackages):
@Configuration
@ComponentScan(basePackages = "com.javaguides.annotations")
class UserConfig {}
Let’s create a very simple Spring boot maven application to showcase the use of Spring
@Component
annotation and how Spring autodetects it with annotation-based
configuration and
classpath scanning.
Add below Spring boot starter web dependency:
<dependency>
<groupId>org.springframework.boot
<artifactId>spring-boot-starter-web
</dependency>
Let’s create a simple component class and mark it with @Component
annotation.
@Component
class ComponentDemo{
public String getValue() {
return "Hello World";
}
}
Spring Container will automatically create and manage the spring bean for the above class because it is
annotated with @Component
annotation.
Note that we have created ApplicationContext and retrieved ComponentDemo bean using getBean() Method.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
ComponentDemo componentDemo = (ComponentDemo) applicationContext.getBean("componentDemo");
System.out.println(componentDemo.getValue());
}
}
@Component
class ComponentDemo {
public String getValue() {
return "Hello World";
}
}
By default, the bean instances of this class have the same name as the class name with a lowercase initial. On top of that, we can specify a different name using the optional value argument of this annotation.
@Component("componentDemo")
class ComponentDemo {
public String getValue() {
return "Hello World";
}
}