Spring @Component

Filed Under: Spring

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.

Spring Component

In layman terms, a Component is responsible for some operations. Spring framework provides three other specific annotations to be used when marking a class as Component.

  1. Service: Denotes that the class provides some services. Our utility classes can be marked as Service classes.
  2. Repository: This annotation indicates that the class deals with CRUD operations, usually it’s used with DAO implementations that deal with database tables.
  3. Controller: Mostly used with web applications or REST web services to specify that the class is a front controller and responsible to handle user request and return appropriate response.

Note that all these four annotations are in package org.springframework.stereotype and part of spring-context jar.

Most of the time our component classes will fall under one of its three specialized annotations, so you may not use @Component annotation a lot.

Spring Component Example

Let’s create a very simple Spring maven application to showcase the use of Spring Component annotation and how Spring autodetects it with annotation-based configuration and classpath scanning.

Create a maven project and add following spring core dependency.


<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>5.0.6.RELEASE</version>
</dependency>

That’s all we need to get the spring framework core features.

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


package com.journaldev.spring;

import org.springframework.stereotype.Component;

@Component
public class MathComponent {

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

Now we can create an annotation based spring context and get the MathComponent bean from it.


package com.journaldev.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringMainClass {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.scan("com.journaldev.spring");
		context.refresh();

		MathComponent ms = context.getBean(MathComponent.class);

		int result = ms.add(1, 2);
		System.out.println("Addition of 1 and 2 = " + result);

		context.close();
	}

}

Just run the above class as normal java application and you should get following output in the console.


Jun 05, 2018 12:49:26 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 12:49:26 IST 2018]; root of context hierarchy
Addition of 1 and 2 = 3
Jun 05, 2018 12:49:26 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 12:49:26 IST 2018]; root of context hierarchy

Did you realized the power of Spring, we didn’t have to do anything to inject our component to spring context.

Below image shows the directory structure of our Spring Component example project.

spring component example

We can also specify the component name and then get it from spring context using the same name.


@Component("mc")
public class MathComponent {
}

MathComponent ms = (MathComponent) context.getBean("mc");
Although I have used @Component annotation with MathComponent, it’s actually a service class and we should use @Service annotation. The result will still be the same.
You can checkout the project from our GitHub Repository.

Reference: API Doc

Comments

  1. Natty says:

    What do you convey to the JVM or Spring context or to the developer by annotating a class as @component or per se as @service ? I don’t get it, could you please elaborate ?

    context.getBean(MathComponent.class);

    Also. What’s the unique difference between @bean vs @component ?

  2. sharat says:

    Gives the following error

    Error occurred during initialization of boot layer

    java.lang.module.FindException: Unable to derive module descriptor for D:\Programming\Spring & Hibernate\[Tutsgalaxy.com] – Spring & Hibernate for Beginners (includes Spring Boot)\7. Spring Configuration with Java Annotations – Inversion of Control\solution-code-spring-annotation-default-component-names\lib\spring-context-indexer-5.1.8.RELEASE-sources.jar

    Caused by: java.lang.module.InvalidModuleDescriptorException: Provider class org.springframework.context.index.processor.CandidateComponentsIndexer not in module

  3. Sohrab Saran says:

    @Component annotation means that only a single instance of the annotated class gets created.
    Also in most cases this instance is automatically created on application startup, perhaps when some other common Spring annotations are used.

    Please let me know if my understanding is correct?

    If yes, then this should be mentioned in the tutorial to give a logic complete picture of what’s happening.

    1. janginay@sina.com says:

      Definitely make sense!

    2. brian says:

      @Component as a default is a singleton, then it was created at application start. If you want it to be created upon declaration then make it a prototype.

  4. Naresh says:

    I am really happy to see that an Indian has posted such a great content / tutorial. I appreciate, I will definitely follow you for more tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages