美文网首页
Spring Boot快速入门之(七):Bean和依赖注入

Spring Boot快速入门之(七):Bean和依赖注入

作者: 码者无疆 | 来源:发表于2020-08-12 16:00 被阅读0次

【注】本文译自:https://www.tutorialspoint.com/spring_boot/spring_boot_beans_and_dependency_injection.htm

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

   }

}

相关文章

网友评论

      本文标题:Spring Boot快速入门之(七):Bean和依赖注入

      本文链接:https://www.haomeiwen.com/subject/kucmdktx.html