Pages

Thursday, April 23, 2020

Spring Boot @Component Annotation - Bean Creation Examples

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());
        
         }
        
        }

No comments:

Post a Comment

Please do not add any spam links in the comments section.