Report this

What is the reason for this report?

Spring @Component

Published on August 3, 2022
Spring @Component

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

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author

Pankaj Kumar
Pankaj Kumar
Author
See author profile

Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev

Category:
Tags:
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.

Still looking for an answer?

Was this helpful?

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

@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

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

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

This example code is not working without @Autowired annotation.

- Sathish

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

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.