春季:为什么我们要自动装配接口而不是实现的类?


interface IA

{

  public void someFunction();

}


@Resource(name="b")

class B implements IA

{

  public void someFunction()

  {

    //busy code block

  }

  public void someBfunc()

  {

     //doing b things

  }

}


@Resource(name="c")

class C implements IA

{

  public void someFunction()

  {

    //busy code block

  }

  public void someCfunc()

  {

     //doing C things

  }

}


class MyRunner

{


  @Autowire

  @Qualifier("b") 

  IA worker;


  worker.someFunction();

}

谁可以给我解释一下这个。


spring如何知道要使用哪种多态类型。

我需要@Qualifier还是@Resource?

为什么我们要对接口而不是已实现的类进行自动装配?


拉丁的传说
浏览 1011回答 2
2回答

万千封印

spring如何知道要使用哪种多态类型。只要接口只有一个实现,并且该实现在@Component启用了Spring的组件扫描的情况下进行注释,Spring框架就可以找出(接口,实现)对。如果未启用组件扫描,则必须在application-config.xml(或等效的spring配置文件)中显式定义Bean。我需要@Qualifier或@Resource吗?一旦拥有多个实现,就需要对每个实现进行限定,并且在自动装配期间,需要使用@Qualifier注释将正确的实现以及@Autowired注释注入。如果使用@Resource(J2EE语义),则应使用name此批注的属性指定Bean名称。为什么我们要对接口而不是已实现的类进行自动装配?首先,一般来说,对接口进行编码始终是一个好习惯。其次,在spring的情况下,您可以在运行时注入任何实现。一个典型的用例是在测试阶段注入模拟实现。interface IA{&nbsp; public void someFunction();}class B implements IA{&nbsp; public void someFunction()&nbsp; {&nbsp; &nbsp; //busy code block&nbsp; }&nbsp; public void someBfunc()&nbsp; {&nbsp; &nbsp; &nbsp;//doing b things&nbsp; }}class C implements IA{&nbsp; public void someFunction()&nbsp; {&nbsp; &nbsp; //busy code block&nbsp; }&nbsp; public void someCfunc()&nbsp; {&nbsp; &nbsp; &nbsp;//doing C things&nbsp; }}class MyRunner{&nbsp; &nbsp; &nbsp;@Autowire&nbsp; &nbsp; &nbsp;@Qualifier("b")&nbsp;&nbsp; &nbsp; &nbsp;IA worker;&nbsp; &nbsp; &nbsp;....&nbsp; &nbsp; &nbsp;worker.someFunction();}您的bean配置应如下所示:<bean id="b" class="B" /><bean id="c" class="C" /><bean id="runner" class="MyRunner" />或者,如果在存在这些组件的软件包上启用了组件扫描,则应按以下步骤对每个类别进行限定@Component:interface IA{&nbsp; public void someFunction();}@Component(value="b")class B implements IA{&nbsp; public void someFunction()&nbsp; {&nbsp; &nbsp; //busy code block&nbsp; }&nbsp; public void someBfunc()&nbsp; {&nbsp; &nbsp; &nbsp;//doing b things&nbsp; }}@Component(value="c")class C implements IA{&nbsp; public void someFunction()&nbsp; {&nbsp; &nbsp; //busy code block&nbsp; }&nbsp; public void someCfunc()&nbsp; {&nbsp; &nbsp; &nbsp;//doing C things&nbsp; }}@Component&nbsp; &nbsp;&nbsp;class MyRunner{&nbsp; &nbsp; &nbsp;@Autowire&nbsp; &nbsp; &nbsp;@Qualifier("b")&nbsp;&nbsp; &nbsp; &nbsp;IA worker;&nbsp; &nbsp; &nbsp;....&nbsp; &nbsp; &nbsp;worker.someFunction();}然后worker在MyRunner中将注入type的实例B。
打开App,查看更多内容
随时随地看视频慕课网APP