2011-05-12 2 views
2

context 컴포넌트 검색이 구성되어있는 한 @Component 주석을 사용하여 스프링 빈을 생성 할 수 있습니까? 자바 6xml bean 정의가없는 스프링 컴포넌트 감지

내 테스트 케이스를 봄 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> 

내 클래스가 나는 콩이되고 싶어요 :

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

스프링이 ServerService 빈을 인스턴스화하고 자동 와이어 링을 수행하기에 충분하지 않아야합니까?

I 얻을 오류 : org.springframework.beans.factory.NoSuchBeanDefinitionException :

자격에 의한 것으로, 적어도 1 빈 : 유형 일치 빈이 [serversystem.ServerService] 의존성 발견 이 종속성에 대한 autowire 후보로. 종속성 주석 : {@ org.springframework.beans.factory.annotation.Autowired (필수 = true)}

나는 뭔가 간단하다고 생각합니다.

답변

6

당신은 당신의 spring-beans.xml<context:component-scan> 요소에 정의되지 않은 :

<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

Perfect. 감사! – wadesworld

0

당신은 컨트롤러 클래스가 저장되어있는 패키지를 지정

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

를 사용해야합니다.