ZetCode

Spring Boot @Component

last modified March 25, 2021

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/Kotlin 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 Kotlin 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.

build
build.gradle.kts
gradle
gradle.properties
gradlew
gradlew.bat
settings.gradle.kts
src
├── main
│   ├── kotlin
│   │   └── com
│   │       └── zetcode
│   │           ├── Application.kt
│   │           ├── MyRunner.kt
│   │           └── service
│   │               └── RandomNameGenerator.kt
│   └── resources
│       └── application.properties
└── test
    ├── kotlin
    └── resources

This is the project structure.

build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    id("org.springframework.boot") version "2.4.4"
    id("io.spring.dependency-management") version "1.0.11.RELEASE"
    kotlin("jvm") version "1.4.31"
    kotlin("plugin.spring") version "1.4.31"
}

group = "com.zetcode"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
}

tasks.test {
    useJUnitPlatform()
}

tasks.withType<KotlinCompile>() {
    kotlinOptions.jvmTarget = "11"
}

This is the Maven build.gradle.kts file. 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.kt
package com.zetcode.service

import org.springframework.stereotype.Component

@Component
class RandomNameGenerator {

    fun generate(): String {

        val names = listOf("Peter", "Roland", "Lucy", "Robert", "Jane")
        return names.random()
    }
}

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

com/zetcode/MyRunner.kt
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
class MyRunner : CommandLineRunner {

    private val logger: Logger = LoggerFactory.getLogger(MyRunner::class.java)

    @Autowired
    private val randGenerator: RandomNameGenerator? = null

    override fun run(vararg args: String?) {

        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 val randGenerator: RandomNameGenerator? = null

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

override fun run(vararg args: String?) {

    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.kt
package com.zetcode

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication

@SpringBootApplication
class Application

fun main(args: Array<String>) {

    runApplication<Application>(*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.

$ ./gradlew bootRun
... 
25-03-2021 10:40:50 [main] INFO  com.zetcode.MyRunner.run - Generating random name: Robert
25-03-2021 10:40:50 [main] INFO  com.zetcode.MyRunner.run - Generating random name: Jane
25-03-2021 10:40:50 [main] INFO  com.zetcode.MyRunner.run - Generating random name: Robert

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.

List Spring Boot tutorials.