5

コード@Injectはあるクラスでは機能しますが、他のクラスでは機能しません。これが私のコードです:

  • context.xml
<?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
                    ">
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
    <context:component-scan base-package="com.myfashions.services"/>
    <context:component-scan base-package="com.myfashions.dao"/>
</beans>
  • SellerRetriever.java
public class SellerRetriever {
    @Inject
    UserDAO userDAO;
    ...
    ...
}

UserDAOクラスはcom.myfashions.daoパッケージに存在します。 @InjectSeller.java で動作していません。何か理由は?

4

3 に答える 3

7

SellerRetrieverとの実装の両方UserDAOに、コンポーネント スキャン用のアノテーションが付けられていることを確認してください。これにより、後者が前者に注入されることが保証されます。

@Service
public class SellerRetriever {
    @Inject
    UserDAO userDAO;
    ...
}

UserDAOで実装に注釈を付け@Componentます。

複数のパスをスキャンする場合は、次を使用します。

<context:component-scan base-package="com.myfashions.services, com.myfashions.dao"/>
于 2013-05-20T12:32:03.853 に答える
3

@Componentスキャンする資格を得るには、クラスにより一般的な、または@Serviceなどの注釈を付ける必要があります@Repositories。あなたの場合、@Service論理的にはより適切です。次に、(必要に応じて) 特にサービス呼び出しに焦点を当てたいくつかの側面 (AOP) を定義できます。

さらに、Bean を取得する@Autowired代わりに使用することもできます。@Inject

これら 2 つの注釈に関する相違点の詳細については、次を参照してください。

Spring Frameworkの@Injectと@Autowiredの違いは何ですか? どのような条件でどちらを使用しますか?

@Autowiredの代わりに保持する正当な理由を説明する私のコメントをすぐ下に見ることができます@Inject

于 2013-05-20T12:22:41.637 に答える
2

間違いを見つけました。誰かが同じ問題を抱えている場合に備えて、これを投稿しています。新しい演算子を使用して、SellerRetriver オブジェクトを作成しました。その特定のクラスを呼び出すために新しい演算子が使用されている場合、注入は機能しません。

于 2013-05-28T06:24:27.843 に答える