2017-12-27 578 views
0

我通過基於XML的配置將Spring框架用於依賴注入。如何使用基於註解的配置來代替基於XML的配置

例如,我有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> 

因此,春天的IoC(容器)將創建四個豆(對象)中所有。

Bean robot1(將引入一個sonyHand bean)。

Bean robot2(將引入一個toshibaHand bean)。

豆sonyHand。

豆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機器人1(將引入sonyHand bean)。

Bean機器人2(同樣會引入sonyHand bean)。

豆sonyHand。

豆toshibaHand。

我知道爲什麼會發生這種情況(因爲@Autowired(「sonyH」)),但我不知道如何解決它的問題,就像使用基於XML的配置一樣。

回答

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 
+0

我很感激你。這解決了我的問題,並最終使我對這個主題的理解變得清晰。 –

+0

很高興幫助:) – pvpkiran

相關問題