@Component in SpringBoot

  • Spring Component annotation is used to denote a class as Component.
  •  A Java class decorated with @Component is found during classpath scanning and registered in the context as a Spring bean.
  • And these classes will be used for dependency Injection when getBean() method is called of ApplicationContext.
  • @Component lies inside org.springframework.stereotype and part of spring-context jar.

Example :

BirdLife.java , this class is marked as component

package GradleDemo;

import org.springframework.stereotype.Component;

@Component
public class BirdLife {
	
	public void haveFood() {
		System.out.println(" Hedwig is eating food");
	}
}

App.java, (Run this class as a Java application)

package GradleDemo;

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

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(App.class, args);
        BirdLife birdLife = applicationContext.getBean(BirdLife.class);
        birdLife.haveFood();
    }

}

build.gradle

plugins {
    id 'java'
    id 'org.springframework.boot' version '2.0.5.RELEASE'
    id 'io.spring.dependency-management' version '1.0.7.RELEASE'
}

repositories {
    jcenter()
}

dependencies {
    implementation 'com.google.guava:guava:28.0-jre'
    testImplementation 'junit:junit:4.12'
    implementation 'org.springframework.boot:spring-boot-dependencies:2.0.5.RELEASE'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'

    components {
        withModule('org.springframework:spring-beans') {
            allVariants {
                withDependencyConstraints {
                    it.findAll { it.name == 'snakeyaml' }.each { it.version { strictly '1.19' } }
                }
            }
        }
    }
}

bootJar {
    mainClassName = 'GradleDemo.App'
}

task runJar{
	dependsOn 'assemble'
	dependsOn 'jar'
	doLast{
  		javaexec { 
    		main="-jar";
    		args = [
            	"build/libs/"+rootProject.name+".jar"
           	]
		} 
	}
}

Leave a Comment