문제

I'm trying to implement some kind of producer factory pattern.
Is it somehow possible to trigger the producer method of a base type while injecting a derived type?

Assuming following interfaces:

interface Service
interface AService extends Service

I want to trigger this producer:

@Produces
Service factory()

At this injection point:

@Inject 
AService srv;

The purpose is to have one producer factory for different kinds of services by adding a marker interface (Service in this case).

Thanks for helping me


Update:

I tried LightGuards solution and added @Typed to the AService implementation:

@Typed(Service.class)
class AServiceImplemenation implements AService 

Unfortunately I get an unsatisfied dependencies error. CDI does't invoke the Service producer for the AService injection point. Certainly, this make sense for typesafty reasons. But is there a way to force the invocation of the Service producer?

도움이 되었습니까?

해결책

If you only have a producer for the super type, and make it so that the AService type doesn't have a no args ctor (or one annotated with @Inject), or is @Typed, or @Vetoed in CDI 1.1 you could return any subclass of Service from your producer.

다른 팁

CDI does not allow producers to produce superclasses, it won't just find a suitable producer for your

@Inject 
AService srv;

I faced the same problem and my solution was:

public class ServiceProxy<T> {
    private final T service;
    public ServiceProxy(T service) {
        this.service = service;
    }
    public T get() {
        return service;
    }
}

interface AService
//something

@Produces
@SomeQualifier
ServiceProxy factory(InjectionPoint ip) {
    Class<?> clazz = (Class<?>) ((ParameterizedType))ip.getType()).getActualTypeArguments()[0];
    //now we know actual service class and can produce one impl
}

@Inject
@SomeQualifier
ServiceProxy<AService> srv;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top