2011-07-06 31 views
7

我是Spring的新手,並且試圖理解下面的概念。Spring Autowire基礎知識

假定accountDAOAccountService的依賴關係。

方案1:

<bean id="accServiceRef" class="com.service.AccountService"> 
    <property name="accountDAO " ref="accDAORef"/> 
</bean> 

<bean id="accDAORef" class="com.dao.AccountDAO"/> 

方案2:

<bean id="accServiceRef" class="com.service.AccountService" autowire="byName"/> 
<bean id="accDAORef" class="com.dao.AccountDAO"/> 

AccountService類:

public class AccountService { 
    AccountDAO accountDAO; 
    .... 
    .... 
} 

在第二種情形中,是如何依賴注入?當我們說它是由Name自動裝配的時候,它究竟是如何完成的。在注入依賴關係時匹配哪個名稱?

在此先感謝!

+0

可能的重複[瞭解Spring @Autowired使用](https://stackoverflow.com/questions/19414734/understanding-spring-autowired-usage) – tkruse

回答

12

使用@Component和@Autowire,它的春天3.0方式

@Component 
public class AccountService { 
    @Autowired 
    private AccountDAO accountDAO; 
    /* ... */ 
} 

將組件掃描在你的應用方面,而不是直接豆聲明。

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
          http://www.springframework.org/schema/beans/spring-beans.xsd 
          http://www.springframework.org/schema/context 
          http://www.springframework.org/schema/context/spring-context.xsd"> 

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

</beans> 
+1

對不起,保羅,但內部這是什麼? – MAlex

+4

組件掃描查找包com中所有註解@Component的類(按照您的示例)和子包。因此,如果您的AccountDAO和AccountService類是@Components,那麼Spring會將其注入到另一箇中。它使用的是類而不是bean的名稱來完成此操作。我認爲這已經成爲使用Spring 3.0將您的依賴關係連接在一起的首選方法。它使您的應用程序上下文更加清晰,並且依賴關係僅在java代碼中表達,他們應該在那裏。 –

+0

謝謝保羅。得到它了。但是,我們不需要使用Spring 3.0的更高版本的Java。我正在使用1.4。我相信在這種情況下,我不能使用註釋。 – MAlex

3
<bean id="accServiceRef" class="com.service.accountService" autowire="byName"> 
</bean>  
<bean id="accDAORef" class="com.dao.accountDAO"> 
</bean> 

public class AccountService { 
    AccountDAO accountDAO; 
    /* more stuff */ 
} 

當春天發現裏面accServiceRef豆的自動裝配屬性,它會掃描AccountService類中的實例變量,匹配名稱。如果任何實例變量名稱與xml文件中的bean名稱匹配,則該bean將被注入到AccountService類中。在這種情況下,找到匹配accountDAO的匹配項。

希望它是有道理的。