Spring-boot-beans-and-dependency-injection

提供:Dev Guides
移動先:案内検索

Beanと依存関係の注入

Spring Bootでは、Spring Frameworkを使用して、Beanとその依存性注入を定義できます。 @ ComponentScan アノテーションは、Beanと @ Autowired アノテーションが挿入された対応するものを見つけるために使用されます。

Spring Bootの一般的なレイアウトに従った場合、 @ ComponentScan アノテーションに引数を指定する必要はありません。 すべてのコンポーネントクラスファイルは、Spring Beanに自動的に登録されます。

次の例は、Rest Templateオブジェクトの自動配線と、同じBeanの作成に関するアイデアを提供します-

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

次のコードは、メインのSpring Boot Applicationクラスファイル内の自動配線されたRest TemplateオブジェクトとBean作成オブジェクトのコードを示しています-

package com.finddevguides.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();
   }
}