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();   
   }
}
广告
© . All rights reserved.