// Tutorial //

Spring @Component

Published on August 3, 2022
Default avatar
By Pankaj
Developer and author at DigitalOcean.
Spring @Component

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Pankaj

author

Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?

may allah bless you. i like the way you share your knowledge with people. than k you sir. best of luck. i m from bangladesh

- pervez ahmed

    This example code is not working without @Autowired annotation.

    - Sathish

      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 ?

      - Natty

        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

        - sharat

          @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.

          - Sohrab Saran

            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.

            - Naresh