首页 > 其他分享 >Spring Boot 注入 Bean 的方法

Spring Boot 注入 Bean 的方法

时间:2023-05-13 16:22:50浏览次数:31  
标签:Spring Boot class Bean List public 注入

阅读完本文 ,你将可以了解到Spring Boot 注入 Bean 的7种方法,分别如下:

  • 通过注解注入的一般形式
  • 通过构造方法注入Bean
  • 通过set方法注入Bean
  • 通过属性去注入Bean
  • 通过List注入Bean
  • 通过Map去注入Bean

背景

我们谈到Spring的时候一定会提到IOC容器、DI依赖注入,Spring通过将一个个类标注为Bean的方法注入到IOC容器中,达到了控制反转的效果。那么我们刚开始接触Bean的时候,一定是使用xml文件,一个一个的注入,就例如下面这样。

 <bean id="bean" class="beandemo.Bean" />

我们的项目一般很大的话,就需要成千上百个Bean去使用,这样写起来就很繁琐。那么Spring就帮我们实现了一种通过注解来实现注入的方法。只需要在你需要注入的类前面加上相应的注解,Spring就会帮助我们扫描到他们去实现注入。

xml扫描包的方式
 <context:component-scan base-package="com.company.beandemo"/>

方法1:通过注解注入的一般形式

一般情况下,注入Bean有一个最直白,最易懂的方式去实现注入,下面废话先不多说,先贴代码。

  • Bean类
 public class MyBean{
 }
  • @Configuration:声明一个类作为配置类,代替xml文件
  • Configuration类
//创建一个class配置文件
 @Configuration
 public class MyConfiguration{
  //将一个Bean交由Spring进行管理
        @Bean
        public MyBean myBean(){
            return new MyBean();
        }
 }

  • Test类

与xml有一点不同,这里在Test中,实例化的不再是ClassPathXmlApplicationContext,而是获取的AnnotationConfigApplicationContext实例。

 ApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
 MyBean myBean = cotext.getBean("myBean",MyBean.class);
 System.out.println("myBean = " + myBean);

上面的代码中MyBean也就是我们需要Spring去管理的一个Bean,他只是一个简单的类。而MyConfiguration中,我们首先用@Configuration注解去标记了该类,这样标明该类是一个Spring的一个配置类,在加载配置的时候会去加载他。

在MyConfiguration中我们可以看到有一个方法返回的是一个MyBean的实例,并且该方法上标注着@Bean的注解,标明这是一个注入Bean的方法,会将下面的返回的Bean注入IOC。

 

 

方法2:通过构造方法注入Bean

我们在生成一个Bean实例的时候,可以使用Bean的构造方法将Bean实现注入。直接看代码

  • Bean类
 @Component
 public class MyBeanConstructor {

     private AnotherBean anotherBeanConstructor;

     @Autowired
     public MyBeanConstructor(AnotherBean anotherBeanConstructor){
         this.anotherBeanConstructor = anotherBeanConstructor;
     }

     @Override
     public String toString() {
         return "MyBean{" +
             "anotherBeanConstructor=" + anotherBeanConstructor +
             '}';
     }
 }

  • AnotherBean类
 @Component(value="Bean的id,默认为类名小驼峰")
 public class AnotherBean {
 }

  • Configuration类
 @Configuration
 @ComponentScan("com.company.annotationbean")
 public class MyConfiguration{
 }

这里我们可以发现,和一般方式注入的代码不一样了,我们来看看新的注解都是什么意思:

  • @AutoWired

简单粗暴,直接翻译过来的意思就是自动装配:wrench:,还不理解为什么叫自动装配:wrench:?看了下一个注解的解释你就知道了。若是在这里注入的时候指定一个Bean的id就要使用@Qualifier注解

  • @Component(默认单例模式)

什么??这翻译过来是零件,怎么感觉像是修汽车??是的,Spring管理Bean的方法就是修汽车的方式。我们在需要将一个类变成一个Bean被Spring可以注入的时候加上注解零件@Conmonent,那么我们就可以在加载Bean的时候把他像零件一样装配:wrench:到这个IOC汽车上了

在这里我们还有几个其他的注解也可以实现这个功能,也就是细化的@Component:

  • @Controller 标注在Controller层

  • @Service 标注在Service层
  • @Repository 标注在dao层
  • @ComponentScan("")

还是翻译,零件扫描,我们去看看括号里的“零件仓库”里面,哪些“零件”(类)需要被装载,Spring就会去扫描这个包,将里面所有标注了@Component的类进行注入。

这里的通过构造方法进行注入就很好理解了,我们在装配MyBean这个零件的时候,突然发现他必须在AnotherBean的基础上才能安装到IOC里面,那么我们就在每次装配MyBean的时候自动装配:wrench:一个AnotherBean进去。举个:chestnut:吧:

还是以汽车为例,我们在踩油门出发之前,是不是必须发车??这里的AutoWired的内容就像发车,你不发车,这个油门你踩断都没有用,他都不会走。

 

方法3:通过set方法注入Bean

我们可以在一个属性的set方法中去将Bean实现注入,看代码吧

  • MyBean类
 @Component
 public class MyBeanSet {

     private AnotherBean anotherBeanSet;

     @Autowired
     public void setAnotherBeanSet(AnotherBean anotherBeanSet) {
         this.anotherBeanSet = anotherBeanSet;
     }

     @Override
     public String toString() {
         return "MyBeanSet{" +
             "anotherBeanSet=" + anotherBeanSet +
             '}';
     }
 }

  • Configuration类 和 Test类

同上一个,就不贴了

这里我们发现在setter方法上我们有一个@AutoWired,与上面不同的是,我们不会在实例化该类时就自动装配:wrench:这个对象,而是在显式调用setter的时候去装配。

setter注入:
public class HelloController {
//    @Autowired
    private Lisi lisi;
    @Autowired
    public void setLisi(Lisi lisi) {
        this.lisi = lisi;
    }

    @GetMapping("/hello")
    public String getHello(){
        lisi.say();
        return "hello world;";
    }
}

 

方法4:通过属性去注入Bean

我们前面两种注入的方式诸如时间不同,并且代码较多,若是通过属性,即就是

 @Component
 public class MyBeanProperty {

     @Autowired
     private AnotherBean anotherBeanProperty;

     @Override
     public String toString() {
         return "MyBeanProperty{" +
             "anotherBeanProperty=" + anotherBeanProperty +
             '}';
     }
 }

这里我们可以看到我们这个类中需要使用AnotherBean这个实例对象,我们可以通过@AutoWired去自动装配它。

对于有些小伙伴问私有属性,Spring怎么去加载它到IOC的?推荐去看看反射

 

方法5:通过List注入Bean

  • MyBeanList类
 @Component
 public class MyBeanList {

     private List<String> stringList;

     @Autowired
     public void setStringList(List<String> stringList) {
         this.stringList = stringList;
     }

     public List<String> getStringList() {
         return stringList;
     }
 }

  • MyConfiguration类
 @Configuration
 @ComponentScan("annoBean.annotationbean")
 public class MyConfiguration {

     @Bean
     public List<String> stringList(){
        List<String> stringList = new ArrayList<String>();
         stringList.add("List-1");
         stringList.add("List-2");
         return stringList;
     }
 }

方法6:我们将MyBeanList进行了注入,对List中的元素会逐一注入。下面介绍另一种方式注入List
  • MyConfiguration类
 @Bean
    //通过该注解设定Bean注入的优先级,不一定连续数字
    @Order(34)
    public String string1(){
        return "String-1";
    }

    @Bean
    @Order(14)
    public String string2(){
        return "String-2";
    }

注入与List中泛型一样的类型,会自动去匹配类型,及时这里没有任何List的感觉,只是String的类型,但他会去通过List的Bean的方式去注入。

第二种方式的优先级高于第一种,当两个都存在的时候,若要强制去使用第一种方式,则要去指定Bean的id即可

 

方法7:

通过Map去注入Bean

 @Component
 public class MyBeanMap {

     private Map<String,Integer> integerMap;

     public Map<String, Integer> getIntegerMap() {
         return integerMap;
     }

     @Autowired
     public void setIntegerMap(Map<String, Integer> integerMap) {
         this.integerMap = integerMap;
     }
 }

 @Bean
    public Map<String,Integer> integerMap(){
        Map<String,Integer> integerMap = new HashMap<String, Integer>();
        integerMap.put("map-1",1);
        integerMap.put("map-2",2);
        return integerMap;
    }

    @Bean
    public Integer integer1(){
        return 1;
    }

    @Bean
    public Integer integer2(){
        return 2;
    }

同样这里也具有两种方式去注入Map类型Bean,且第二种的优先值高于第一种

以上就是Bean通过注解注入的几种方式,大家可以对比着xml注入的方式去看。

标签:Spring,Boot,class,Bean,List,public,注入
From: https://www.cnblogs.com/youxin/p/17397588.html

相关文章

  • 野火Linux uboot编译/烧录/移植学习
    首先,要说野火的linux驱动的pdf做得不是很好,代码内容匆匆略过。后来才发现野火有专门的网页,这是驱动部分的章节:https://doc.embedfire.com/lubancat/build_and_deploy/zh/latest/index.html代码都可以下载!!!预备:添加编译器相关①学习:立即生效添加交叉工具链,需要修改/etc/profi......
  • Spring
    什么是SpringSpring可理解为一个巨大的容器,里面由多种组件(bean)组合合成,每个组件有自己的职责和生命周期,组件之间有相互依赖的关系。构建bean目前有两种方式来构建bean,XML或者java注解,新版的Spring也推荐我们使用注解的方式来定义bean,我们跟随官方的脚步来看看bean的定义:@Co......
  • spring框架_@AutoWiredAnnotationBeanPostProcessor执行分析
    AutoWiredAnnotationBeanPostProcessor执行依赖注入的时候(解析@Autowired)调用了postProcessProperties方法这个方法首先要找到哪些属性,方法被标注了@Autowired注解,把这些数据添加到InjectMetadata中,然后调用metadata.inject方法按类型进行依赖注入,注入时按类型进行查找按类......
  • 创建SpringCloud项目
    SpringCloud简介SpringCloud是目前国内使用最广泛的微服务框架。SpringCloud集成了各种微服务功能组件,并基于SpringBoot实现了这些组件的自动装配,从而提供了良好的开箱即用体验。SpringCloud常用组件1.服务注册发现:Eureka,Nacos,Consul2.服务远程调用:OpenFeign,Dubbo3.服务链路......
  • HBuilderX快捷键Netbeans版本
    [//删除选中行{"key":"ctrl+e","command":"editor.action.deleteLines","override":true},//在当前行下方插入空行并把光标移动到新行{"key":"shift+enter","command":"editor.action.insertLineAfter"......
  • SpringBoot整合Mybatis
    SpringBoot整合MyBatisSpringBoot整合MyBatisSpringBoot是一个快速开发应用程序的框架,而MyBatis是一个提供ORM支持的优秀框架。在本文中,我们将学习如何将SpringBoot与MyBatis整合,以便我们能够更加轻松地开发Web应用程序。步骤创建新的SpringBoot项目。在pom.xml文件中添加My......
  • Spring---AOP的实现
    AOP使用AOP进行代理开发的话,需要导入这样一个依赖:<!--https://mvnrepository.com/artifact/org.aspectj/aspectjweaver--><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.6<......
  • java基于springboot+vue的农机电招平台、农机租赁管理系统,附源码+数据库+文档+PPT,适合
    1、项目介绍该系统包括前台操作和后台管理两个部分,一方面,为用户提供首页,农机,系统公告,个人中心,后台管理等功能;另一方面,为管理员提供首页,个人中心,农机机主管理,使用者管理,农机类型管理,农机管理,农机预约管理,系统管理等功能。项目获取,看这里2、技术框架编程语言:java系统架构:B/S......
  • Netbeans加入CI的代码提示
    最近想选用一个轻量级的IDE配合CI开发,能够正确代码提示的都比较少,要不得Zend于是下载了Netbeans6.8,想按照http://www.yinzhili.com/2009/08/using-code-completion-for-codeigniter-in-netbeans.html的教程,把System添加到Netbeans的库里以便支持CI提示,但是不知道哪一步出了......
  • SpringBoot 依赖注入方式
    前置知识SpringDI(DependencyInjection)依赖注入:组件之间依赖关系由容器在运行期间决定,即由容器动态的将某个依赖关系注入到组件中谁依赖谁:应用程序依赖IOC容器为什么需要依赖:应用程序需要IOC容器提供对象需要的外部资源谁注入谁:IOC容器注入应用程序某个对象,应用程序依赖的......