2011-07-06 70 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的匹配项。

希望它是有道理的。