2

Is there any way to inject a concrete implementation of @Produces returned interface?

SomeClassImpl implements SomeClass {
    public Integer iField;
}

Producer class:

@Produces
public SomeClass produceChild(){
    SomeClassImpl impl = new SomeClassImpl();
    impl.iField = 17;
    return impl;
}

Consumer class:

@Inject SomeClassImpl classImpl;

EDIT

The attempt to @Inject SomeClassImpl doesn't force container to use the @Produces method that returns super-type SomeClass.

Why it is possible to inject child-type via @Inject parent-type (without Producer), but no variants inject child-type via @Produces parent-type ?

blacktide
  • 10,654
  • 8
  • 33
  • 53
uptoyou
  • 1,427
  • 19
  • 24
  • Use [qualifiers](https://docs.oracle.com/javaee/6/tutorial/doc/gjbck.html) if you have more than one implementation of an interface – ares May 15 '16 at 14:14
  • See [this answer](http://stackoverflow.com/questions/22982422/cdi-ambiguous-dependency-with-produces-why). – blacktide May 15 '16 at 14:24
  • In regards to your edit, because your `@Produces` method produces a `SomeClass` instance, not a `SomeClassImpl` instance, which could return any implementation of `SomeClass`, not just `SomeClassImpl` instances. You can fix it by injecting `SomeClass` (not the implementation) and using a qualifier, or by modifying your `@Produces` method to return `SomeClassImpl`. – blacktide May 15 '16 at 19:31
  • I got it, thanks, but i need to inject exactly SomeClassImpl type via Produces method. If its not possible - tell me please "This is not possible!" =)) – uptoyou May 15 '16 at 19:39

1 Answers1

1

You can use @Typed to control what the valid types are for your bean. https://docs.jboss.org/cdi/api/1.0/javax/enterprise/inject/Typed.html

John Ament
  • 11,595
  • 1
  • 36
  • 45