2011-05-12 9 views
2

contextコンポーネントのスキャンが設定されている限り、@Component注釈だけを使用してSpring Beanを作成できるのは正しいですか?xml bean定義のないSpringコンポーネントの検出

のJava 6

で春3.0.5を使用して私のテストケースがある:

@ContextConfiguration(locations={"classpath:spring-bean.xml"}) 

public class ServerServiceUnitTest extends AbstractJUnit4SpringContextTests { 
    @Autowired 
    private ServerService serverService; 

    @Test 
    public void test_server_service() throws Exception { 
      serverService.doSomething(); 
      //additional test code here 
     } 
} 

spring-bean.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-3.0.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
    <context:annotation-config/> 
</beans> 

私のクラスIは、Beanになりたいれます:

@Component("ServerService") 
public class ServerServiceImpl implements ServerService { 
    private static final String SERVER_NAME = "test.nowhere.com"; 
     //method definitions.....' 
} 

SpringがServerService beanをインスタンス化してオートワイヤリングを行うのに十分ではないでしょうか?

私が手にエラーがある:org.springframework.beans.factory.NoSuchBeanDefinitionException:

起因する資格期待少なくとも1豆:タイプの一致するBeanが[serversystem.ServerService]依存性は見つかりませんこの依存関係のautowire候補として。依存関係の注釈:{@ org.springframework.beans.factory.annotation.Autowired(必須= true)}

私は何かが簡単ではないと確信しています。あなたのspring-beans.xml<context:component-scan>要素で定義されていない

答えて

6

<context:component-scan base-package="the.package.with.your.service"/> 

<context:annotation-config/> 

を含めることは、あなたが設定のため@Required@Autowired、および@Inject注釈を使用することができます。 <context:component-scan>を指定すると、Springに@Componentの注釈を検索する場所が示されます。あなたは

<mvc:annotation-driven/> 

を含める必要があります 注釈付きのコントローラやその他の機能を使用している場合

+0

パーフェクト。ありがとう! – wadesworld

0

あなたは、コントローラクラスが格納されているパッケージを指定する

<context:component-scan base-package="spring3.example.controllers"/> 

を使用する必要があります。

関連する問題