Ebooks

Spring Boot @Component

Spring Boot @Component tutorial shows how to use the @Component annotation in a Spring application. In the example, we create a Spring Boot console application.

Spring is a popular Java application framework and Spring Boot is an evolution of Spring that helps create stand-alone, production-grade Spring based applications easily.

@Component

@Component is the most generic Spring annotation. A Java class decorated with @Component is found during classpath scanning and registered in the context as a Spring bean. @Service, @Repository, and @Controller are specializations of @Component, which are used for more specific cases.

@ComponentScan ensures that the classes decorated with @Component are found and registered as Spring beans. @ComponentScan is automatically included with @SpringBootApplication.

@Bean servers a similar purpose as @Component. It is not autodetected. Methods decorated with @Bean produce a bean to be managed by the Spring container during configuration stage.

Spring Boot @Component example

The following application demonstrates the usage of @Component. It uses the annotation to create a bean that randomly generates names.

pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           │   Application.java
│   │           │   MyRunner.java
│   │           └───service
│   │                   RandomNameGenerator.java
│   └───resources
│           application.properties
└───test
    └───java

This is the project structure.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>springbootcomponentex</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

This is the Maven pom.xml file. The spring-boot-starter-parent is a parent POM providing dependency and plugin management for applications built with Maven. The spring-boot-starter is a core starter, including auto-configuration support, logging, and YAML. The spring-boot-maven-plugin packages Spring applications into executable JAR or WAR archives.

resources/application.properties
spring.main.banner-mode=off
logging.level.org.springframework=ERROR
logging.pattern.console=%d{dd-MM-yyyy HH:mm:ss} %magenta([%thread]) %highlight(%-5level) %logger.%M - %msg%n

The application.properties is the main configuration file in Spring Boot. We turn off the Spring banner, reduce the amount of logging of the Spring framework by selecting only error messages, and set the console logging pattern

com/zetcode/service/RandomNameGenerator.java
package com.zetcode.service;

import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Random;

@Component
public class RandomNameGenerator {

    public String generate() {

        var names = List.of("Peter", "Roland", "Lucy", "Robert", "Jane");

        var r = new Random();
        int i = r.nextInt(names.size());

        return names.get(i);
    }
}

The RandomNameGenerator is a Java class decorated with @Component. It will be detected during component scan process and registered as a Spring bean.

com/zetcode/MyRunner.java
package com.zetcode;

import com.zetcode.service.RandomNameGenerator;
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 MyRunner implements CommandLineRunner {
    
    private static final Logger logger = LoggerFactory.getLogger(MyRunner.class);

    @Autowired
    private RandomNameGenerator randGenerator;

    @Override
    public void run(String... args) {
        
        logger.info("Generating random name: {}", randGenerator.generate());
        logger.info("Generating random name: {}", randGenerator.generate());
        logger.info("Generating random name: {}", randGenerator.generate());
    }
}

By implementing the CommandLineRunner, the run() method of the MyRunner class will be executed after the application starts.

@Component
public class MyRunner implements CommandLineRunner {

MyRunner is also decorated with @Component, so it will be autodetected and registered as well.

@Autowired
private RandomNameGenerator randGenerator;

With the @Autowired annotation, we inject the RandomNameGenerator bean into the randGenerator field.

@Override
public void run(String... args) {
    
    logger.info("Generating random name: {}", randGenerator.generate());
    logger.info("Generating random name: {}", randGenerator.generate());
    logger.info("Generating random name: {}", randGenerator.generate());
}

In the run() method, we log messages containing random names.

com/zetcode/Application.java
package com.zetcode;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application  {
    
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Application is the entry point which sets up Spring Boot application. The @SpringBootApplication annotation enables auto-configuration and component scanning. It is a convenience annotation for @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations.

$ mvn -q spring-boot:run 
...
30-04-2019 12:22:44 [main] INFO  com.zetcode.MyRunner.run - Generating random name: Roland
30-04-2019 12:22:44 [main] INFO  com.zetcode.MyRunner.run - Generating random name: Peter
30-04-2019 12:22:44 [main] INFO  com.zetcode.MyRunner.run - Generating random name: Lucy

After the application is run, we can see the log messages in the console.

In this tutorial, we have shown how to use @Component annotation in a Spring application. You might also be interested in the related tutorials: Spring Boot @Controller tutorial, Spring Boot @Repository tutorial, Java tutorial, or list all Spring Boot tutorials.