Bean 和依賴注入



在 Spring Boot 中,我們可以使用 Spring 框架來定義我們的 Bean 及其依賴注入。@ComponentScan 註解用於查詢 Bean,並使用@Autowired 註解進行相應的注入。

如果您遵循 Spring Boot 的典型佈局,則無需為@ComponentScan 註解指定任何引數。所有元件類檔案都會自動註冊到 Spring Bean 中。

以下示例提供了一個關於自動裝配 Rest Template 物件和為此建立 Bean 的思路:

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

以下程式碼顯示了在主 Spring Boot 應用程式類檔案中自動裝配 Rest Template 物件和 Bean 建立物件的程式碼:

DemoApplication.java

package com.tutorialspoint.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();   
   }
}
廣告