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:
Java Program to Generate Random Numbers Using Multiply with Carry Method
Simplify the DAO with Spring and Java Generics
Write/Read cookies using HTTP and Read a file from the internet
Spring Boot - Build Systems
Guide to Selenium with JUnit / TestNG
Different Ways to Capture Java Heap Dumps
Bootstrapping Hibernate 5 with Spring
Using Spring @ResponseStatus to Set HTTP Status Code
Giới thiệu Google Guice – Aspect Oriented Programming (AOP)
A Guide to the Java ExecutorService
Hướng dẫn Java Design Pattern – Dependency Injection
Convert Hex to ASCII in Java
Java Program to Implement Treap
An Intro to Spring Cloud Contract
What is Thread-Safety and How to Achieve it?
Create Java Applet to Simulate Any Sorting Technique
Spring Security Login Page with React
Tổng quan về ngôn ngữ lập trình java
Debug a HttpURLConnection problem
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?
Guide to ThreadLocalRandom in Java
Java Program to implement Associate Array
Working with Kotlin and JPA
Java Program to Perform Stooge Sort
Guide to Apache Commons CircularFifoQueue
Java Program to Implement Extended Euclid Algorithm
Java Program to Implement Solovay Strassen Primality Test Algorithm
Overview of Spring Boot Dev Tools
@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll
Quick Guide to Spring MVC with Velocity
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
Java Timer