Spring 弹簧自动线基础

Spring 弹簧自动线基础,spring,Spring,我是一个春天的新手,正在努力理解下面的概念 假设accountDAO是AccountService的依赖项 情景1: <bean id="accServiceRef" class="com.service.AccountService"> <property name="accountDAO " ref="accDAORef"/> </bean> <bean id="accDAORef" class="com.dao.AccountDAO"/&

我是一个春天的新手,正在努力理解下面的概念

假设
accountDAO
AccountService
的依赖项

情景1:

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

<bean id="accDAORef" class="com.dao.AccountDAO"/>
在第二个场景中,依赖关系是如何注入的?当我们说它是通过名称自动连接的时候,它是如何完成的呢。在指定依赖项时匹配了哪个名称


提前谢谢

使用@Component和@Autowire,这是Spring 3.0的方式

@Component
public class AccountService {
    @Autowired
    private AccountDAO accountDAO;
    /* ... */
}   
在应用程序上下文中进行组件扫描,而不是直接声明bean

<?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>

当spring在
accServiceRef
bean中找到autowire属性时,它将扫描
AccountService
类中的实例变量以查找匹配的名称。如果任何实例变量名与xml文件中的bean名匹配,则该bean将被注入
AccountService
类。在本例中,找到了
accountDAO
的匹配项


希望它有意义。

抱歉,Paul,但在内部这有什么作用?组件扫描会在包com(根据您的示例)和子包中查找所有带注释的@Component类。因此,如果您的AccountDAO和AccountService类是@Components,那么Spring将把一个注入另一个。它使用类而不是bean的名称来实现这一点。我认为这已经成为使用Spring3.0将依赖项连接在一起的首选方法。它使您的应用程序上下文更加清晰,依赖项完全用java代码表示,它们应该在java代码中表达。谢谢Paul。知道了。但是,我们不需要更高的java版本来使用Spring3.0吗。我使用的是1.4。我相信在这种情况下,我不能使用注释。Java1.4在将近三年前就已经过时了。如果可以的话,我建议您使用Java6
@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>
<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 */
}