Spring Autowire基础知识 [英] Spring Autowire Fundamentals

查看:113
本文介绍了Spring Autowire基础知识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring的新手,正试图了解以下概念.

I am a newbie in Spring and am trying to understand the below concept.

假定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自动接线时,它是如何完成的.增强依赖性时匹配哪个名称?

In the second scenario, How is the dependency injected ? When we say it is autowired by Name , how exactly is it being done. Which name is matched while injecing the dependency?

提前谢谢!

推荐答案

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

Use @Component and @Autowire, it's the Spring 3.0 way

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

在应用程序上下文中放置组件扫描,而不是直接声明Bean.

Put a component scan in your app context rather than declare the beans directly.

<?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 Autowire基础知识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆