Tutorial

Spring @Component

Published on August 3, 2022
Default avatar

By Pankaj

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

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

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
May 29, 2020

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

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    January 2, 2020

    This example code is not working without @Autowired annotation.

    - Sathish

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      November 20, 2019

      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

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        August 14, 2019

        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

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          October 10, 2018

          @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

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            September 13, 2018

            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

              Try DigitalOcean for free

              Click below to sign up and get $200 of credit to try our products over 60 days!

              Sign up

              Join the Tech Talk
              Success! Thank you! Please check your email for further details.

              Please complete your information!

              Get our biweekly newsletter

              Sign up for Infrastructure as a Newsletter.

              Hollie's Hub for Good

              Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

              Become a contributor

              Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

              Welcome to the developer cloud

              DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

              Learn more
              DigitalOcean Cloud Control Panel