English 中文(简体)
Spring Boot Tutorial

Spring Boot Resources

Selected Reading

Spring Beans & Dependency Injection
  • 时间:2024-11-03

Beans and Dependency Injection


Previous Page Next Page  

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
pubpc 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 Apppcation class file −

package com.tutorialspoint.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApppcation;
import org.springframework.boot.autoconfigure.SpringBootApppcation;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cpent.RestTemplate;

@SpringBootApppcation
pubpc class DemoApppcation {
@Autowired
   RestTemplate restTemplate;
   
   pubpc static void main(String[] args) {
      SpringApppcation.run(DemoApppcation.class, args);
   }
   @Bean
   pubpc RestTemplate getRestTemplate() {
      return new RestTemplate();   
   }
}
Advertisements