Spring Autowire Fundamentals

MAl*_*lex 7 spring

我是春天的新手,我试图理解下面的概念.

假设这accountDAO是一个依赖AccountService.

场景1:

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

<bean id="accDAORef" class="com.dao.AccountDAO"/>
Run Code Online (Sandbox Code Playgroud)

场景2:

<bean id="accServiceRef" class="com.service.AccountService" autowire="byName"/>
<bean id="accDAORef" class="com.dao.AccountDAO"/>
Run Code Online (Sandbox Code Playgroud)

AccountService课堂上:

public class AccountService {
    AccountDAO accountDAO;
    ....
    ....
}
Run Code Online (Sandbox Code Playgroud)

在第二种情况下,如何注入依赖?当我们说它是由Name自动装配时,它究竟是如何完成的.在引入依赖项时匹配哪个名称?

提前致谢!

Pau*_*zie 12

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

@Component
public class AccountService {
    @Autowired
    private AccountDAO accountDAO;
    /* ... */
}   
Run Code Online (Sandbox Code Playgroud)

将组件扫描放在应用程序上下文中,而不是直接声明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>
Run Code Online (Sandbox Code Playgroud)

  • Java 1.4在大约三年前就已经过了.我建议,如果可以的话,你可以自己学习Java 6. (6认同)
  • 组件扫描查找包com中的所有类注释@Component(根据您的示例)和子包.因此,如果您的AccountDAO和AccountService类是@Components,那么Spring会将一个注入另一个.它使用类而不是bean的名称来执行此操作.我认为这已成为使用Spring 3.0将依赖项连接在一起的首选方法.它使您的应用程序上下文更清晰,依赖关系仅在Java代码中表达,它们应该在那里. (4认同)