Spring Boot 教程:Bean和依赖注入

379 阅读1分钟

【注】本文译自: www.tutorialspoint.com/spring_boot…   在Spring Boot 中,我们可以利用 Spring Framework 定义 bean 及其依赖注入。@ComponentScan 及其对应的 @Autowired 注解被用于发现和注入 bean。   如果你遵循典型的 Spring Boot 代码结构,那么就不需要使用 @ComponentScan 注解的任何参数。所有的组件类文件都被注册为 Spring Beans。   下面的示例说明如何自动注入 Rest Template 对象并创建一个相同的:

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

  以下代码展示如何在主Spring Boot 应用类文件中自动注入 Rest Template 对象及其 Bean 对象:

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();   
   }
}