2014-01-15 2 views
3

문제 : 나는 콩으로 서비스를 주입하려고봄 주입 자원은 항상 null

하지만 서비스 인스턴스는 항상 null입니다.

배경 :

나는 두 콩 다른 호출을 가지고있다.

<context:annotation-config /> 
<bean class="com.test.MyBeanImpl" name="myBean"/> 
<bean id="myService" class="com.test.MyServiceImpl" /> 

와 콩과 같이 구현됩니다 :

MyServiceImpl.java

class MyServiceImpl implements MyService { 
    public void getString() { 
     return "Hello World"; 
    } 
} 

MyBeanImpl.java

@Component 
class MyBeanImpl implements MyBean, SomeOtherBean1, SomeOtherBean2 { 
    @Resource(name="myBean") 
    private MyService myService; 

    public MyBeanImpl() {} 
} 
이 그들이 XML의 설정에서 정의하는 방법이다

질문 :

내 콩이 서비스를 주입하지 못하게하는 3 개의 인터페이스를 구현한다는 것과 관련된 몇 가지 이유가 있습니까? 그렇지 않은 경우 다른 요소가 영향을 미칠 수 있습니까?

+0

당신이의 클래스 선언을 게시 할 수있는이 문제를 해결할 수는

<context:annotation-config /> <context:component-scan base-package="com.mypackage" /> 

희망으로 운영자 파일에 <context:component-scan /> 요소 패키지의 이름을 언급 확인 클래스'MyService'와 전체 구성을 주입하려고합니까? –

+0

더 많은 정보가 포함되도록 OP를 업데이트했습니다. 기본적으로 MyService 인터페이스 또는 구현 클래스에는 주석이 없습니다. 건배 – travega

+0

빈 설정 파일에''가 포함되어 있지 않으면'@ Resource'가 작동하지 않는다고 생각합니다. 내가 게시 한 요지를보십시오. 나는 시험을했고 작동한다. 그것이 귀하의 필요를 충족시키지 못하면 귀하의 상황이 어떻게 다른지 알려주십시오. –

답변

5

당신이 주석을 사용하는 것처럼 그냥 @Service 주석 서비스 클래스를 표시하고 서비스 클래스의

MyServiceImpl.java

package com.mypackage.service; 
@Service 
class MyServiceImpl implements MyService { 

    public void getString() { 
     return "Hello World"; 
    } 
} 

MyBeanImpl을 인스턴스를 얻을 수 @Autowired 주석을 사용 .자바 또한

@Component 
class MyBeanImpl implements MyBean, SomeOtherBean1, SomeOtherBean2 { 

    @Autowired 
    private MyService myService; 

    public MyBeanImpl() {} 
} 

1

MyService을 삽입 할 빈이 빈인지 확인하십시오. 또한

/* This must be a bean, either use @Component or place in configuration file */ 
@Component 
public class SomeClass{ 
    @Resource 
    private MyService myService; 
} 

구성에서 응용 프로그램을 사용하여 주석 기반 구성을 사용하도록 지정했는지 확인하십시오

<context:annotation-config/> 

당신의 이름으로 빈을 한정 여러 인터페이스 그것을 가장 할 수있다 사용하기 때문에 :

<bean class="com.test.MyBeanImpl" name="myBean" /> 

그런 다음 @Resource 주석에 이름 요소를 지정

@Resource(name="myBean") 
private MyService myService; 

다음은 이러한 개념을 설명하는 Github Gist입니다.

+0

안녕하세요 Kevin, 먼저 Git Gist를 만드는 노력에 감사드립니다. MyApp로 정의한 bean은 3 개의 인터페이스를 구현하는 bean이고 MyServiceImpl bean은 하나의 인터페이스 "MyService"를 구현한다는 점에서 약간의 차이점이 있습니다. 위의 제안을 시도 할 때 "MyBeanImpl"이라는 "SomeClass"가 있기 때문에 "myBean"이라는 Bean이 없다는 배포 오류가 발생합니다. OP를 업데이트하여 명확하게 만듭니다. – travega