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:
Hướng dẫn sử dụng Java Generics
Spring Cloud – Bootstrapping
Hướng dẫn Java Design Pattern – Visitor
Logging a Reactive Sequence
Java InputStream to String
CyclicBarrier in Java
Từ khóa static và final trong java
Introduction to Netflix Archaius with Spring Cloud
Lập trình đa luồng trong Java (Java Multi-threading)
A Guide to the ViewResolver in Spring MVC
Spring Boot Configuration with Jasypt
Java 9 Stream API Improvements
Checked and Unchecked Exceptions in Java
Java Program to Search for an Element in a Binary Search Tree
Java Program to implement Bi Directional Map
Spring’s RequestBody and ResponseBody Annotations
Giới thiệu Java 8
Introduction to Using Thymeleaf in Spring
Java Program to Find the GCD and LCM of two Numbers
Spring MVC Custom Validation
A Guide to Java SynchronousQueue
Intro to Spring Boot Starters
MyBatis with Spring
Finding Max/Min of a List or Collection
Using Spring ResponseEntity to Manipulate the HTTP Response
Getting Started with Forms in Spring MVC
Unsatisfied Dependency in Spring
Marker Interface trong Java
Build a REST API with Spring and Java Config
Java Program to Implement Levenshtein Distance Computing Algorithm
Java Program to Check if a Given Binary Tree is an AVL Tree or Not
Model, ModelMap, and ModelAndView in Spring MVC