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:
JUnit5 Programmatic Extension Registration with @RegisterExtension
HashSet trong java
Java Program to Implement Heap
Java Program to Perform Preorder Recursive Traversal of a Given Binary Tree
Guide to Guava Multimap
Hướng dẫn Java Design Pattern – Adapter
RegEx for matching Date Pattern in Java
Java Program to Solve TSP Using Minimum Spanning Trees
Intro to Spring Boot Starters
Guide to @JsonFormat in Jackson
Spring Boot - Admin Client
Java 8 Stream API Analogies in Kotlin
@Order in Spring
Guide to Escaping Characters in Java RegExps
Explain about URL and HTTPS protocol
Send email with JavaMail
Java Program to Find Basis and Dimension of a Matrix
Java Program to implement Priority Queue
Jackson Exceptions – Problems and Solutions
Control the Session with Spring Security
Using Java Assertions
Java Program to Implement Binary Tree
Java – Combine Multiple Collections
Allow user:password in URL
Java – InputStream to Reader
Java Program to Implement Sparse Array
Getting a File’s Mime Type in Java
Concurrent Test Execution in Spring 5
Find the Registered Spring Security Filters
Introduction to Spring Security Expressions
Spring RestTemplate Error Handling
Registration – Password Strength and Rules