Component

Before we can understand the value of @Component, we first need to understand 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.

Bean management and the opportunity for dependency injection are some of Spring's main features.

Using the Inversion of Control principleSpring collects bean instances from our application and uses them at the appropriate time. We can show bean dependencies to Spring without needing to handle the setup and instantiation of those objects.

Spring Component annotation is used to denote a class as Component. It means that Spring framework will autodetect these classes for dependency injection when annotation-based configuration and classpath scanning is used.

Example:

Let’s create a simple component class and mark it with @Component annotation

@Component
public class MathComponent implements IMathModule{

	public int add(int x, int y) {
		return x + y;
	}
}

Now instead of instantiating our math module directly, Spring will automatically get the correct class we need. If we have multiple implementations of IMathModule, we can tell Spring which one to use without having to manually change the class in every place the implementation is referenced

public class Main {

	@Autowired
	private IMathModule mathModule;

	public static void main(String[] args) {
		int result = mathModule.add(1,3);
	}

}