如何使用基于注释的配置代替基于XML的配置

时间:2017-12-27 16:08:39

标签: java xml spring

我通过基于XML的配置将Spring框架应用于依赖注入。

例如,我有3个班级:

  1. public class Robot implements IRobot{

       IHand hand;

       -//-

     }

  2. public class SonyHand implements IHand{ -//- }

  3. public class ToshibaHand implements IHand{ -//- }

此外,我有XML文件:

<beans ...>

  <bean id="robot1" class="somepackage.Robot.class">
    <property name="hand" ref="sonyHand">
  </bean>

  <bean id="robot2" class="somepackage.Robot.class">
    <property name="hand" ref="toshibaHand">
  </bean>

  <bean id="sonyHand" class="somepackage.SonyHand.class"/>


  <bean id="toshibaHand" class="somepackage.ToshibaHand.class"/>       

</beans>

因此,Spring IoC(容器)将在所有中创建四个bean(对象)。

Bean robot1(将在其中引入sonyHand bean)。

Bean robot2(将引入toshibaHand bean)。

Bean sonyHand。

Bean toshibaHand。

问题是,我可以通过基于纯注释的配置做同样的事情吗?如果我这样做,那怎么样?我试过这个:

@Configuration
public class AppConfig{

  @Bean
  public Robot robot1(){
    return new Robot();
  }

  @Bean
  public Robot robot2(){
    return new Robot();
  }

  @Bean
  @Qualifier("sonyH")
  public SonyHand sonyHand(){
    return new SonyHand();
  }

  @Bean
  @Qualifier("toshibaH")
  public ToshibaHand toshibaHand(){
    return new ToshibaHand();
  }
}

稍微改变了类:

  1. public class Robot implements IRobot{

       @Autowired("sonyH")
       IHand hand;

       -//-

     }

  2. public class SonyHand implements IHand{ -//- }

  3. public class ToshibaHand implements IHand{ -//- }

XML文件中几乎没有任何内容:

<beans ...>

  <context:component-scan base-package="somepackage"/>    

</beans>

这一切都有效,但这不是我需要的,因为容器创建的bean与前面的例子略有不同:

Bean robot1(将在其中引入sonyHand bean)。

Bean robot2(将再次引入sonyHand bean)。

Bean sonyHand。

Bean toshibaHand。

而且我知道为什么会发生这种情况(因为@Autowired(“sonyH”)),但我不知道如何修复它,使其像基于XML的配置一样工作。

1 个答案:

答案 0 :(得分:1)

略微重构你的课程

@Configuration
public class AppConfig{

  @Bean
  public Robot robot1(IHand sonyH){
    return new Robot(sonyH);
  }

  @Bean
  public Robot robot2(IHand toshibaH){
    return new Robot(toshibaH);
  }

  @Bean(name = "sonyH")
  public SonyHand sonyHand(){
    return new SonyHand();
  }

  @Bean(name = "toshibaH")
  public ToshibaHand toshibaHand(){
    return new ToshibaHand();
  }
}

现在,如果您尝试像这样自动装配

@Autowired
Robot robot1 // this will have sonyH instance

@Autowired
Robot robot2 // this will have toshibaH instance