Beans and Dependency Injection

In Spring Boot, we can use Spring Framework to define our beans and their dependency injection. The @ComponentScan annotation is used to find beans and the corresponding injected with @Autowired annotation.

If you followed the Spring Boot typical layout, no need to specify any arguments for @ComponentScan annotation. All component class files are automatically registered with Spring Beans.

The following example provides an idea about Auto wiring the Rest Template object and creating a Bean for the same −

@Bean
public RestTemplate getRestTemplate() {
   return new RestTemplate();
}

The following code shows the code for auto wired Rest Template object and Bean creation object in main Spring Boot Application class file −

package com.maixuanviet.demo;

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;

@SpringBootApplication
public class DemoApplication {
@Autowired
   RestTemplate restTemplate;
   
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @Bean
   public RestTemplate getRestTemplate() {
      return new RestTemplate();   
   }
}

Related posts:

Spring 5 and Servlet 4 – The PushBuilder
Java Program to Check whether Undirected Graph is Connected using DFS
Java Program to Find kth Largest Element in a Sequence
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Các nguyên lý thiết kế hướng đối tượng – SOLID
Spring 5 WebClient
Java – String to Reader
The Basics of Java Security
How to Use if/else Logic in Java 8 Streams
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
Java Program to Implement Kosaraju Algorithm
Hướng dẫn Java Design Pattern – State
Java Program to Implement Ternary Search Tree
Java Program to Implement Merge Sort Algorithm on Linked List
Spring Security Remember Me
Implementing a Runnable vs Extending a Thread
Overview of the java.util.concurrent
Spring Security Authentication Provider
Java Program to Check if a Point d lies Inside or Outside a Circle Defined by Points a, b, c in a Pl...
Java 8 Predicate Chain
Registration – Activate a New Account by Email
A Guide to Spring Cloud Netflix – Hystrix
Configure a Spring Boot Web Application
A Guide To UDP In Java
Java Program to Implement Repeated Squaring Algorithm
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
Spring Boot - Service Components
Registration with Spring Security – Password Encoding
Java Program to Find the Mode in a Data Set
Immutable Map Implementations in Java
Java Program to Implement Network Flow Problem