A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

Beans and Dependency Injection in Spring Boot

Beans and Dependency Injection in Spring Boot

Beans and Dependency Injection in Spring Boot

Let's understand first here that what is a bean in spring and how did we use the IOC in spring framework?

What is Beans in Spring?

  • The objects that form the backbone of your application

  • The objects that are managed by the Spring IoC container are called beans.

  • A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.

  • A bean is simply one of many objects in your application.

Let's see in the application, how beans get initialized for spring application:

Beans in Spring Boot

  • The @ComponentScan annotation is used to find beans in spring framework.

  • These beans are being injected with @Autowired annotation.

  • But, there is no need to specify any arguments for @ComponentScan annotation in the Spring Boot.

  • All component class files are registered with Spring Beans automatically.

This is very easy example to understand the auto-wiring the Rest Template object and creating a Bean for the same

              package com.techieuncle.app;
              import org.springframework.beans.factory.annotation.Autowired;
              import org.springframework.boot.SpringApplication;
              import org.springframework.boot.autoconfigure.SpringBootApplication;
              import org.springframework.context.annotation.Bean;
              import org.springframework.web.client.RestTemplate;

              public class ExampleApplication {
                 RestTemplate restTemplate;

                 public static void main(String[] args) {
                    SpringApplication.run(ExampleApplication.class, args);
                 public RestTemplate findRestTemplate() {
                    return new RestTemplate();