2014-09-12 4 views
1

Java EE CDI, 종속성 삽입 및 특히 @Produces을 배우고 있습니다. 내가 getGreedingCard() 메서드에서 왜 @Produces 주석이 필요한지 궁금합니다. GreetingCardImplAnotherGreetingCardImpl 두 클래스가 이미 공간으로 가져 왔기 때문에 주석이 전혀 필요하지 않습니다. 이는 정규 패키지/클래스 종속성과 동일하며 간단한 가져 오기로 문제가 해결됩니다. @producer 주석을 사용하여 종속성 주입이 필요한 이유는 무엇입니까?Java EE의 @Producer 주석

미리 감사드립니다.

public interface GreetingCard { 
    void sayHello(); 
} 


public class GreetingCardImpl implements GreetingCard { 

    public void sayHello() { 
     System.out.println("Hello!!!"); 
    } 
} 


public class AnotherGreetingCardImpl implements GreetingCard { 

    public void sayHello() { 
     System.out.println("Have a nice day!!!"); 
    } 
} 

import com.javacodegeeks.snippets.enterprise.cdibeans.impl.AnotherGreetingCardImpl; 
import com.javacodegeeks.snippets.enterprise.cdibeans.impl.GreetingCardImpl; 

@SessionScoped 
public class GreetingCardFactory implements Serializable { 

    private GreetingType greetingType; 

    @Produces 
    public GreetingCard getGreetingCard() { 
     switch (greetingType) { 
      case HELLO: 
       return new GreetingCardImpl(); 
      case ANOTHER_HI: 
       return new AnotherGreetingCardImpl(); 
      default: 
       return new GreetingCardImpl(); 
     } 
    } 
} 
+0

테스트 해 보셨습니까? GreetingCard는 3 개의 장소 (2 개의 클래스와 프로듀서 메소드)로 작성 될 수 있으므로, AmbiguousResolutionException을 가져야합니다. 관련 링크에 대한 링크 http://stackoverflow.com/q/22982422/3701228 – Gas

답변

1

두 클래스 GreetingCardImpl 및 AnotherGreetingCardImpl 이미 공간으로 수입하고 있기 때문에 getGreedingCard() 메서드는, 그것이 전혀 @Produces 주석을 필요로하는 이유가 궁금.

글쎄, getGreetingCard에 @Produces 주석이 필요하지 않습니다. 중요한 것은 다른 클래스가 의존성 주입을 통해 GreetingCards를 수신 할 수있게하는 것입니다.

public class Foo { 

@Inject // <--- will invoke @Producer method 
GreetingCard foosGreetingCard 

... 

} 

은 자세한 내용은 here를 참조하십시오

생산자 방식은 콩 인스턴스의 소스 역할을하는 방법이다. 메소드 선언 자체는 지정된 컨텍스트에 인스턴스가 없을 때 bean 및 컨테이너를 설명합니다. 은 메소드를 호출하여 bean의 인스턴스를 확보합니다. 당신이 공장 빈을 주입 및 인스턴스를 생성하는 직접 방법을 사용하고 greetingCard 콩 themseleves를 주입하지 될 것입니다 귀하의 경우

+0

제공된 링크에서 Jan은 "자체적으로 임의의 숫자 인 Bean 클래스를 작성할 수는 없지만 확실히 난수를 반환하는 메서드를 작성하십시오. " 왜 우리는 그 자체로 난수 인 클래스를 작성할 수 없습니까?모든 클래스는 bean 양식으로 작성 될 수 있습니다. 권리? – marlon

+0

그와는 무관 한 문제입니다. SOF에서는 일반적으로 주석을 사용하지 않고 새로운 질문을 시작합니다. 그렇지 않으면 읽고 이해하기가 정말 어려워집니다. –

0

@Produces 필요하지 않습니다. 당신이 @Produces 방법 및 GreetingCard를 주입하는 시도로 정의 할 경우

@Inject 
GreetingCardFactory factory; 

... 

GreetingCard card = factory.getGreetingCard(); 

, 당신은 내가 코멘트에 기술 한 예외를 얻을 것입니다. 당신은 또한이 같은 규정 생성 할 경우

그러나 :

@Qualifier 
@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE}) 
public @interface ProducedCard {} 

및 생산자 방식에 추가 :

@Produces @ProducedCard 
public GreetingCard getGreetingCard() { 
... 

는 당신이 사용하는 단지 GreetingCard 콩을 주입 할 수있을 것입니다 당신의 생산자 방식 :

@Inject @ProducedCard 
GreetingCard card; 

@ProducedCard :-)로 표시된 인사말 카드를 만드는 장소가 하나 밖에 없으므로 다시 모호하지 않습니다.

관련 문제