2011-07-06 5 views
7

私は春の初心者で、以下の概念を理解しようとしています。春のオートワイヤーの基礎

accountDAOAccountServiceの依存関係であるとします。

シナリオ1:

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

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

シナリオ2:AccountServiceクラスで

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

:2番目のシナリオで

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

、どのように依存関係が注入されますか?私たちが名前によってautowiredであると言うとき、それはいかに正確に行われていますか。依存関係を突きつけているときに一致する名前はどれですか?

ありがとうございます!

+0

[Spring @Autowired usage](https://stackoverflow.com/questions/19414734/understanding-spring-autowired-usage)の可能な複製 – tkruse

答えて

12

使用@Componentと@Autowire、それ

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

春3.0の方法は、アプリのコンテキストでコンポーネントのスキャンを置くのではなく、直接豆を宣言しています。

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

Paulに感謝します。とった。しかし、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豆内部autowire性を検出すると、一致する名前のためAccountServiceクラス内のインスタンス変数をスキャンします。インスタンス変数名のいずれかがxmlファイルのBean名と一致する場合、そのBeanはAccountServiceクラスに挿入されます。この場合、accountDAOの一致が見つかりました。

希望します。