spring boot beans 和 依赖注入——迹忆客-ag捕鱼王app官网

在 spring boot 中,我们可以使用 spring framework 来定义我们的 bean 及其依赖注入。 @componentscan 注解用于查找 bean 和相应的使用@autowired 注解来实现注入。

如果我们遵循 spring boot 典型布局,则无需为 @componentscan 注解指定任何参数。 所有组件类文件都会自动注册到 spring beans。

以下示例提供了有关自动连接 rest template 对象并为其创建 bean

@bean
public resttemplate getresttemplate() {
   return new resttemplate();
}

以下代码显示了主 spring boot application 类文件中自动装配的 resttemplate 对象和 bean 创建对象的代码

package com.study;
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 myapplication {
@autowired
   resttemplate resttemplate;
   
   public static void main(string[] args) {
      springapplication.run(myapplication.class, args);
   }
   @bean
   public resttemplate getresttemplate() {
      return new resttemplate();   
   }
}

查看笔记

扫码一下
查看教程更方便
网站地图