spring依赖注入的四种方式,spring依赖注入的两种方式

  spring依赖注入的四种方式,spring依赖注入的两种方式

  

目录
环境准备设值注入构造注入总结

  

环境

Ubuntu 22.04 intellij IDEA 2022。1 .3 JDK 17。0 .3春5。3 .21

  

准备

创建专家项目测试0706 .

  修改pom.xml文件,添加依赖:

  .-https://mvn repository.com/artifact/JUnit/JUnit-依赖关系groupId JUnit/groupId artifact id JUnit/artifact id版本4 .13 .2/版本scope test/scope/dependence!-https://mvn存储库。com/artifact/org。spring框架/spring-web MVC-依赖groupIdorg.springframework/groupId artifact id版本5 . 3 . 21/版本/依赖性.在资源中心/主要/资源目录下创建应用程序上下文。可扩展标记语言文件:

  ?可扩展标记语言版本=1.0 编码=utf-8 ?豆子xmlns= http://www。spring框架。org/schema/beans xmlns : xsi= http://www。w3。org/2001/XML schema-instance xsi :架构位置= http://www。spring框架。org/schema/beans http://www。spring框架。org/schema/beans/beans/spring-beans。xsd /bean在src/test/java目录下创建测试:

  公共类Test0706 {}

  

设值注入

创建如下POJO:

  斧头:斧头接口;石斧:斧头实现类;钢斧:斧头实现类;人:人持有斧头;包持久化类公共接口axe { public void chop();}包持久化类公共类石斧实现斧子{公共石斧(){系统。出去。println(石斧构造者);} @覆盖public void chop(){ system。出去。println(石斧!);} }包pojopublic类钢斧实现斧{公钢斧(){系统。出去。println(钢斧构造者);} @覆盖public void chop(){ system。出去。println(钢斧!);}}

  e>

package pojo;public class Person { private String name; private Axe axe; public void setAxe(Axe axe) { this.axe = axe; } public void setName(String name) { this.name = name; } public void useAxe() { System.out.println("I am " + name); axe.chop(); } public Person() { System.out.println("Person constructor"); }}
applicationContext.xml 中注册bean:

  

 ...... <bean id="stoneAxe" class="pojo.StoneAxe"/> <bean id="steelAxe" class="pojo.SteelAxe"/> <bean id="person" class="pojo.Person"> <property name="name" value="Tom"/> <property name="axe" ref="stoneAxe"/> </bean> ......
创建测试用例:

  

 @Test public void test1() { var ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println("before getBean"); var person = ctx.getBean("person", Person.class); person.useAxe(); }
运行测试,如下:

  

StoneAxe constructorSteelAxe constructorPerson constructorbefore getBeanI am TomStone axe!

  

总结:

  一般的bean(相对工厂bean)是在Spring初始化时创建的(注意:默认的scope是 singleton ,如果是 prototype ,则是在每次 getBean() 的时候创建实例对象);可以直接注入值( value ),也可以注入bean( ref );被注入的bean(如本例中的 stoneAxe )在 Person 之前实例化;具体如何注入呢?是通过反射来调用Person的setter方法,其中方法名是字符串拼起来的,具体来讲是 set 加上首字母大写的 属性名 。本例中, person 有一个属性叫做 axe ,则Spring会拼出 setAxe() 方法,并把 ref 的对象作为参数传进去。所以,一定要确保Person有对应的方法;

  

构造注入

构造注入和设值注入非常相像,二者的主要区别为:

  设值注入是通过setter方法来注入被依赖对象;构造注入是通过构造方法来注入被依赖对象;创建如下POJO:

  Book :Book接口;PlayBook :Book实现类;StudyBook :Book实现类;Student :Student持有Book;

package pojo;public interface Book { public void show();}
package pojo;public class PlayBook implements Book{ public PlayBook() { System.out.println("PlayBook constructor"); } @Override public void show() { System.out.println("Play book!"); }}
package pojo;public class StudyBook implements Book{ public StudyBook() { System.out.println("StudyBook constructor"); } @Override public void show() { System.out.println("Study book!"); }}
package pojo;public class Student { private String name; private Book book; public Student(String name, Book book) { System.out.println("Student constructor"); this.name = name; this.book = book; } public void readBook() { System.out.println("I am " + name); book.show(); }}
applicationContext.xml 中注册bean:

  

 ...... <bean id="playBook" class="pojo.PlayBook"/> <bean id="studyBook" class="pojo.StudyBook"/> <bean id="student" class="pojo.Student"> <constructor-arg index="0" value="Jerry"/> <constructor-arg index="1" ref="playBook"/> </bean> ......
创建测试用例:

  

 @Test public void test2() { var ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println("before getBean"); var student = ctx.getBean("student", Student.class); student.readBook(); }
运行测试,如下:

  

......PlayBook constructorStudyBook constructorStudent constructorbefore getBeanI am JerryPlay book!

  

总结:

  一般的bean(相对工厂bean)是在Spring初始化时创建的(注意:默认的scope是 singleton ,如果是 prototype ,则是在每次 getBean() 的时候创建实例对象);可以直接注入值( value ),也可以注入bean( ref );被注入的bean(如本例中的 PlayBook )在 Student 之前实例化;具体如何注入呢?是通过反射来调用bean的构造方法,如果有多个参数,可以用 index 来区分(下标从 0 开始),所以一定要确保有对应的构造方法; 接口注入接口注入和设值注入也很相像,都是通过setter方法来注入被依赖对象,二者的主要区别为:

  接口注入需要实现特定接口,因此setter方法是固定的;在设值注入中,被注入的具体对象是我们自己定的,而在接口注入中,被注入的对象是Spring决定的,我们不需要配置 <property> 来注入对象;以 ApplicationContextAware 接口为例,在Spring初始化时,会扫描所有的bean,如果发现某个bean实现了该接口,就会自动调用其 setApplicationContext() 方法,把Spring容器本身传进去;

  创建POJO MyBean

  

package pojo;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;public class MyBean implements ApplicationContextAware { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println("before setter"); this.applicationContext = applicationContext; } public void foo() { System.out.println(applicationContext.getDisplayName()); }}
applicationContext.xml 中注册bean:

  

 ...... <bean id="myBean" class="pojo.MyBean"/> ......
创建测试用例:

  

 @Test public void test3() { var ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println("before getBean"); var myBean = ctx.getBean("myBean", MyBean.class); myBean.foo(); }
运行测试,如下:

  

......before setterbefore getBeanorg.springframework.context.support.ClassPathXmlApplicationContext@506e6d5e

  

总结:

  无需配置注入对象;具体如何注入呢?Spring会扫描所有的bean,如果发现某个bean实现了某些接口,就会自动调用其接口方法,把特定对象(比如Spring容器本身)传进去; 自动装配对于bean之前的依赖关系,通常我们使用 ref 来显式指定被注入的对象。Spring也支持自动装配(autowire)。

  常见的自动装配策略有:

  byName :通过setter方法名来查找bean ID,跟前面说的通过bean ID来调用setter方法正好相反。具体操作为:去掉 set 前缀,然后首字母小写。比如 setName() 方法,得到的bean ID是 name 。如果找不到对应的bean ID,则不进行注入操作。由于ID是唯一的,所以不存在找到多个bean的情况;byType :根据setter方法的参数类型来查找bean,如果找不到符合的bean,则不进行注入操作。如果找到多个符合的bean,则抛出异常;创建如下POJO:

  Ball:Ball接口;FootBall :Ball实现类;BasketBall :Ball实现类;Athlete :Athlete持有Ball;

package pojo;public interface Ball { public void fly();}
package pojo;public class FootBall implements Ball{ @Override public void fly() { System.out.println("FootBall is flying"); }}
package pojo;public class BasketBall implements Ball{ @Override public void fly() { System.out.println("BasketBall is flying"); }}
package pojo;public class Athlete { private Ball ball; public void setBall(Ball ball) { this.ball = ball; } public void play() { ball.fly(); }}
applicationContext.xml 中注册bean:

  

 ...... <bean id="footBall" class="pojo.FootBall"/> <bean id="basketBall" class="pojo.BasketBall"/> <bean id="athlete" class="pojo.Athlete" autowire="byName"/> ......
创建测试用例:

  

 @Test public void test4() { var ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); var athlete = ctx.getBean("athlete", Athlete.class); athlete.play(); }
运行测试,如下:

  

java.lang.NullPointerException: Cannot invoke "pojo.Ball.fly()" because "this.ball" is null

  

这是因为 autowire="byName" ,setter方法为 setBall() 。移除 set 前缀,并把首字母 B 变成 b ,所以会查找ID为 ball 的bean,但是没有找到,所以不会注入对象。但是后面调用了Ball的 fly() 方法,所以报了空指针错误。

  修改配置如下:

  

 ...... <bean id="ball" class="pojo.FootBall"/> <bean id="basketBall" class="pojo.BasketBall"/> <bean id="athlete" class="pojo.Athlete" autowire="byName"/> ......
再次运行测试,这次成功了:

  

FootBall is flying
修改配置,把 byName 改为 byType

  

 ...... <bean id="athlete" class="pojo.Athlete" autowire="byName"/> ......
再次运行测试,如下:

  

org.springframework.beans.factory.UnsatisfiedDependencyException:Error creating bean with name 'athlete' defined in class path resource [applicationContext.xml]:Unsatisfied dependency expressed through bean property 'ball';nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException:No qualifying bean of type 'pojo.Ball' available:expected single matching bean but found 2: ball,basketBall

  

找到了多个符合的bean,所以报错了。

  修改配置,只保留一个Ball的实现类:

  

 ......<!-- <bean id="ball" class="pojo.FootBall"/>--> <bean id="basketBall" class="pojo.BasketBall"/> <bean id="athlete" class="pojo.Athlete" autowire="byType"/> ......
再次运行测试,这次成功了。

  

BasketBall is flying

  

  

总结

Bean默认的scope是 singleton ,表示在Spring初始化的时候创建,如果设置为 prototype ,则是在每次 getBean() 的时候创建实例对象(注:工厂bean创建bean行为有所不同,即使是singleton,也不是在Spring初始化时创建,而是在第一次 getBean() 时创建,参见我另一篇文档)。可以直接注入值( value ),也可以注入bean( ref );被注入的bean(如本例中的 stoneAxe )在 Person 之前实例化;具体如何注入呢?

  设值注入:通过反射来调用bean的setter方法,其中方法名是字符串拼起来的,具体来讲是 set 加上首字母大写的 属性名 。所以,一定要确保bean有对应的方法;构造注入:通过反射来调用bean的构造方法,如果有多个参数,可以用 index 来区分(下标从 0 开始),所以一定要确保有对应的构造方法;接口注入:无需配置注入对象。Spring会扫描所有的bean,如果发现某个bean实现了某些接口,就会自动调用其接口方法,把特定对象(比如Spring容器本身)传进去;自动装配 :

  byName :通过setter方法名来查找bean ID,跟前面说的通过bean ID来调用setter方法正好相反。把setter方法名去掉 set 前缀,然后首字母小写。比如对于 setName() 方法,得到的bean ID是 name

  如果找不到对应的bean ID,则不进行注入操作;如果找到对应的bean ID,则进行注入操作;由于ID是唯一的,所以不存在找到多个bean ID的情况;byType :根据setter方法的参数类型来查找bean:

  如果找不到符合的bean,则不进行注入操作;如果找到唯一符合的bean,则进行注入操作;如果找到多个符合的bean,则抛出异常;到此这篇关于Spring依赖注入的几种方式分享梳理总结的文章就介绍到这了,更多相关Spring依赖注入内容请搜索盛行IT以前的文章或继续浏览下面的相关文章希望大家以后多多支持盛行IT!

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

相关文章阅读

  • spring编程式事务处理,spring编程事务
  • spring编程式事务处理,spring编程事务,详解Spring学习之编程式事务管理
  • spring的核心功能模块有几个,列举一些重要的spring模块
  • spring的核心功能模块有几个,列举一些重要的spring模块,七个Spring核心模块详解
  • spring注解和springmvc的注解,SpringMVC常用注解
  • spring注解和springmvc的注解,SpringMVC常用注解,详解springmvc常用5种注解
  • spring实现ioc的四种方法,spring的ioc的三种实现方式
  • spring实现ioc的四种方法,spring的ioc的三种实现方式,简单实现Spring的IOC原理详解
  • spring事务失效问题分析及解决方案怎么做,spring 事务失效情况
  • spring事务失效问题分析及解决方案怎么做,spring 事务失效情况,Spring事务失效问题分析及解决方案
  • spring5.0新特性,spring4新特性
  • spring5.0新特性,spring4新特性,spring5新特性全面介绍
  • spring ioc以及aop原理,springmvc aop原理
  • spring ioc以及aop原理,springmvc aop原理,深入浅析Spring 的aop实现原理
  • Spring cloud网关,spring cloud zuul作用
  • 留言与评论(共有 条评论)
       
    验证码: