我通过基于XML的配置应用Spring框架进行依赖注入(inject)。
例如,我有 3 个类(class):
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 东芝手。
问题是,我可以通过纯基于注释的配置来做完全相同的事情吗?如果我这样做,那又如何?我试过这个:
@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 robots2(并且将再次将 sonyHand bean 引入其中)。
Bean sonyHand。
bean 东芝手。
我知道为什么会发生这种情况(因为 @Autowired("sonyH")),但我不知道如何修复它,使其像基于 XML 的配置一样工作。
最佳答案
稍微重构你的类
@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();
}
}
现在,如果您尝试像这样 Autowiring
@Autowired
Robot robot1 // this will have sonyH instance
@Autowired
Robot robot2 // this will have toshibaH instance
关于java - 如何使用基于注释的配置代替基于 XML 的配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47995229/