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.

$ tree
.
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── zetcode
    │   │           ├── Application.java
    │   │           ├── bean
    │   │           │   └── RandomNameGenerator.java
    │   │           └── MyRunner.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>SpringBootComponent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.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.

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

RandomNameGenerator.java
package com.zetcode.bean;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.springframework.stereotype.Component;

@Component
public class RandomNameGenerator {
    
    public String generate() {
        
        List<String> names = new ArrayList<>();
        
        names.add("Peter");
        names.add("Roland");
        names.add("Lucy");
        names.add("John");
        names.add("Robert");
        names.add("Jane");
        
        Random 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.

MyRunner.java
package com.zetcode;

import com.zetcode.bean.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) throws Exception {
        
        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) throws Exception {
    
    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.

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 
...
15-12-2017 18:50:33 [main] INFO com.zetcode.MyRunner.run - Generating random name: Jane
15-12-2017 18:50:33 [main] INFO com.zetcode.MyRunner.run - Generating random name: Peter
15-12-2017 18:50:33 [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 @PostConstruct tutorial, Spring Boot @Controller tutorial, Spring Boot @ExceptionHandler tutorial, Spring Boot upload file, Spring Boot @PathVariable tutorial, Spring Boot @RequestParam tutorial, Spring Boot @ResponseBody tutorial, Java tutorial.