? ?本文讲解spirng三种注入方式(构造函数注入,setter注入,注解注入)中的构造函数注入。
? ?所有例子,都是以注解的方式注册bean。
? ?关于构造函数方式注入,春官网的说明地址为:春官网之构造函数注入
引用>1。构造函数只有一个参数且类型为单个实现类
单参数且单实现类这是一种最简单的以构造函数的注入方式注入依赖,只要在构造函数中添加所依赖类型的参数即可,春天会匹配对应类型的bean进行注入,由于只有一个对应类型的实现类,因此能准确地找到bean进行注入。
引用>我们看以下例子:
<李>创建一个接口:李>
<代码>公共接口GoPlay { 公共空间havePlay (); } 代码> >之前<李>创建一个实现类李>
<代码>进口org.springframework.stereotype.Component; @ component 公共类GoPlayImpl实现GoPlay { @Override 公共空间havePlay () { system . out。println (“\ n \ nsingle玩\ n \ n”); } } 代码> >之前<李>再创建一个具体类,依赖于GoPlay接口,以构造函数方式注入:李>
<代码>进口org.springframework.stereotype.Component; @ component 公开课PlayController { 私人GoPlay GoPlay; 公共PlayController (GoPlay GoPlay) { 这一点。goPlay=goPlay; } 公共空间玩(){ goPlay.havePlay (); } }代码><李>用单元测试验证一下是否能将GoPlay唯一的实现类注入到PlayController中:李>
<代码>进口org.junit.After; 进口org.junit.Test; 进口org.junit.runner.RunWith; 进口org.springframework.boot.test.context.SpringBootTest; 进口org.springframework.test.context.junit4.SpringRunner; 进口javax.annotation.Resource; @RunWith (SpringRunner.class) @SpringBootTest 公开课PlayControllerTest { @ PlayController PlayController; @After 公共空间tearDown()抛出异常{ } @Test 公共空间玩(){ playController.play (); } }代码>//有一些自动生成的函数没有删除
<李>执行测试用例,执行结果打印如下:李>
<代码>单独玩 代码> >之前说明成功地将对应的bean以构造函数的方式注入。
2。参数依赖类型有多实现类情况下的注入方式
单构造函数参数依赖的类型,有多个实现类时,就不能直接像上面的例子一样,只定义接口的类型了:
以下方式是错误的:
<代码>公共MorePlayContorller (MorePlay MorePlay) { morePlay.someOnePlay (); }代码>需要写明所引用的bean的名称,否则春根据类型匹配到两个bean,就会报错。
引用>看下实际的例子:
<李>声明一个接口:
<代码>公共接口MorePlay { 公共空间someOnePlay (); }代码>李> <李>第一个实现类:李><代码>进口org.springframework.stereotype.Component; @ component 公共类MorePlayImplFirstOne实现MorePlay { @Override 公共空间someOnePlay () { system . out。println (“\ n \ nFirst一玩。\ n \ n”); } } 代码> >之前<李>第二个实现类:李>
<代码>进口org.springframework.stereotype.Component; @ component 公共类MorePlayImplSecondOne实现MorePlay { @Override 公共空间someOnePlay () { system . out。println (“\ n \ nSecond一玩。\ n \ n”); } } 代码> >之前<李>以构造函数方式注入以上定义类型(下面这个例子会注入失败):李>
<代码>进口org.springframework.stereotype.Component; @ component 公开课MorePlayContorller { 私人MorePlay MorePlay; 公共MorePlayContorller (MorePlay MorePlay) { morePlay.someOnePlay (); } } 代码> >之前<李>写一个测试用例验证一下:李>
<代码>进口org.junit.Test; 进口org.junit.runner.RunWith; 进口org.springframework.boot.test.context.SpringBootTest; 进口org.springframework.test.context.junit4.SpringRunner; 进口javax.annotation.Resource; @RunWith (SpringRunner.class) @SpringBootTest 公开课MorePlayContorllerTest { @ MorePlayContorller MorePlayContorller; @Test 公共空间玩(){ morePlayContorller.play (); } }春天构造函数注入方式详解