Bean和依赖注入,在Spring Boot 中,我们可以使用 Spring Framework 来定义我们的 bean 及其依赖注入。@ComponentScan注解用于查找bean,对应注入@Autowired注解。
如果您遵循 Spring Boot 典型布局,则无需为@ComponentScan注释指定任何参数。所有组件类文件都自动注册到 Spring Beans。
以下示例提供了有关自动连接 Rest 模板对象并为其创建 Bean 的想法 –
@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(); } }