$show=/label

Spring Boot @Component Annotation - Bean Creation Examples

SHARE:

A practical guide to @Component annotation in Spring Boot with examples to create beans. If you define @Component on any class, then this class will be scanned and auto detected for dependency injection. Finally, Registers with the application context.

Spring Boot @Component

1. Introduction


In this article, We'll learn how to use @Component annotation in spring or sprig boot application. This looks similar to the use of @Bean annotation and can be used for bean creation.

2. Spring or Spring Boot @Component Annotation


@Component annotation is a class-level annotation that can not be used on the method level. If you define any class with @Component annotation that should be known to the spring application context.
How to make the component class scanned by spring boot is to specify the package of the class to @ComponentScan annotation or use @SpringBootApplication(scanBasePackages = "com.javaprogramto.component").

Spring Boot @Component Annotation - Bean Creation Examples



By default, Spring Boot scans the @SpringBootApplication class package, and it's all sub-packages. So, If your component class is outside of this base package then the new package needs to specified with attribute scanBasePackages=" new package location".

Subsequently, It scans the current package and additional packages. Hence, all classes will be registered with the container.

3. Spring @Component - Bean Creation Example


Next, let us create an example class with @Component annotation.

As I told above, Keeping the below class in the same package where the main class is present.

[package com.javaprogramto.bean.create.beancreation;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class ComponentExample {
Logger logger = LoggerFactory.getLogger(getClass());
@PostConstruct
public void printMessage() {
logger.info("@Component object is registered with the context.");
}
}]

Observe the above class that is created with @Component annotation.

Furthermore, How to check whether the bean is registered with the spring container or not?

The answer is that we need to make a method annotated with @PostConstruct which will be executed after bean creation with all dependencies and registered with the container.

4. Running Main Spring Boot Application


Just run the below program that creates all the things need to run the spring applications without any additional furthermore configurations.

[package com.javaprogramto.bean.create.beancreation;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BeanCreationApplication {
public static void main(String[] args) {
SpringApplication.run(BeanCreationApplication.class, args);
}
}]


Output:

From consolded output, you can see the logger content is written from the @PostConstruct annotation.
 [ .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.6.RELEASE)
2020-04-23 11:53:15.245  INFO 11159 --- [           main] c.j.b.c.b.BeanCreationApplication        : Starting BeanCreationApplication on -Pro-2.local with PID 11159 (/Users/venkateshn/Documents/VenkY/blog/workspace/untitled folder/bean-creation/target/classes started by venkateshn in /Users/venkateshn/Documents/VenkY/blog/workspace/untitled folder/bean-creation)
2020-04-23 11:53:15.248  INFO 11159 --- [           main] c.j.b.c.b.BeanCreationApplication        : No active profile set, falling back to default profiles: default
2020-04-23 11:53:15.762  INFO 11159 --- [           main] c.j.b.c.beancreation.ComponentExample     : Component object is registered with the context.
2020-04-23 11:53:15.819  INFO 11159 --- [           main] c.j.b.c.b.BeanCreationApplication        : Started BeanCreationApplication in 1.224 seconds (JVM running for 1.834)]

5. @Component Annotation Example To Generate Random Numbers


Another example program to generate random integer numbers with @Component and @Autowired annotation.

Random Number generator class:


[package com.javaprogramto.bean.create.beancreation;
import java.util.Random;
import org.springframework.stereotype.Component;
@Component
public class NumberGenerator {
public Integer getNumber() {
Random random = new Random();
Integer randomValue = random.nextInt();
return randomValue;
}
}]

Command-line runner class :


In the below class, we have autowired the NumberGenerator class and invoking getNumber() multiple times that generate a new number every time.

To visible the runner class to the container, the NumberGeneratorRunner class must be annotated with @Component. So that container can see this and executes it's run() method.

[package com.javaprogramto.bean.create.beancreation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class NumberGeneratorRunner implements CommandLineRunner {
Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private NumberGenerator generator;
@Override
public void run(String... args) throws Exception {
logger.info("Random number : " + generator.getNumber());
logger.info("Random number : " + generator.getNumber());
logger.info("Random number : " + generator.getNumber());
logger.info("Random number : " + generator.getNumber());
logger.info("Random number : " + generator.getNumber());
}
}]

Note: All of these classes are placed in the base package where our @SpringBootApplication annotated class is present and all of these scanned by default. So that we can eliminate adding @ComponentScan explicitly.

Output:

It has been generated unique values for each time getNumber() is invoked from runner class.


[2020-04-23 13:06:42.454  INFO 13768 --- [           main] c.j.b.c.b.NumberGeneratorRunner          : Random number : -452668592
2020-04-23 13:06:42.454  INFO 13768 --- [           main] c.j.b.c.b.NumberGeneratorRunner          : Random number : -756539981
2020-04-23 13:06:42.454  INFO 13768 --- [           main] c.j.b.c.b.NumberGeneratorRunner          : Random number : 1775959422
2020-04-23 13:06:42.454  INFO 13768 --- [           main] c.j.b.c.b.NumberGeneratorRunner          : Random number : -1296993058
2020-04-23 13:06:42.454  INFO 13768 --- [           main] c.j.b.c.b.NumberGeneratorRunner          : Random number : 1400439998]

6. Conclusion


To summarize, we've seen What is @Component annotation and how to use this. Example programs on @Component to generate the random numbers.

As usual, The examples code shown in this article is over GitHub.

[lock]

[View on GitHub ##eye##]

[Download ##file-download##]

[/lock]
  • [accordion]
    • ComponentExample.java
      • package com.javaprogramto.bean.create.beancreation;
        
        import javax.annotation.PostConstruct;
        
        import org.slf4j.Logger;
        import org.slf4j.LoggerFactory;
        import org.springframework.stereotype.Component;
        
        @Component
        public class ComponentExample {
        
         Logger logger = LoggerFactory.getLogger(getClass());
        
         @PostConstruct
         public void printMessage() {
        
          logger.info("@Component object is registered with the context.");
         }
        
        }
    • NumberGenerator.java
      • package com.javaprogramto.bean.create.beancreation;
        
        import java.util.Random;
        
        import org.springframework.stereotype.Component;
        
        @Component
        public class NumberGenerator {
        
         public Integer getNumber() {
        
          Random random = new Random();
          Integer randomValue = random.nextInt();
          return randomValue;
         }
        
        }
    • NumberGeneratorRunner.java
      • package com.javaprogramto.bean.create.beancreation;
        
        import org.slf4j.Logger;
        import org.slf4j.LoggerFactory;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.boot.CommandLineRunner;
        import org.springframework.stereotype.Component;
        
        @Component
        public class NumberGeneratorRunner implements CommandLineRunner {
        
         Logger logger = LoggerFactory.getLogger(getClass());
        
         @Autowired
         private NumberGenerator generator;
        
         @Override
         public void run(String... args) throws Exception {
          logger.info("Random number : " + generator.getNumber());
          logger.info("Random number : " + generator.getNumber());
          logger.info("Random number : " + generator.getNumber());
          logger.info("Random number : " + generator.getNumber());
          logger.info("Random number : " + generator.getNumber());
        
         }
        
        }

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Spring Boot @Component Annotation - Bean Creation Examples
Spring Boot @Component Annotation - Bean Creation Examples
A practical guide to @Component annotation in Spring Boot with examples to create beans. If you define @Component on any class, then this class will be scanned and auto detected for dependency injection. Finally, Registers with the application context.
https://1.bp.blogspot.com/-RP44VQ46ILQ/XqF4VNeOyMI/AAAAAAAACfo/To4VMBvAcrYI-y8_tJcbqD2gyEK3WfiBQCLcBGAsYHQ/s400/Spring%2BBoot%2B%2540Component%2BAnnotation%2B-%2BBean%2BCreation%2BExamples.png
https://1.bp.blogspot.com/-RP44VQ46ILQ/XqF4VNeOyMI/AAAAAAAACfo/To4VMBvAcrYI-y8_tJcbqD2gyEK3WfiBQCLcBGAsYHQ/s72-c/Spring%2BBoot%2B%2540Component%2BAnnotation%2B-%2BBean%2BCreation%2BExamples.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/04/spring-boot-component-annotation.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/04/spring-boot-component-annotation.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content