chzbrgla
chzbrgla

Reputation: 5188

CDI: @Produces method is not injecting after invoking Instance with an AnnotationLiteral

I'm trying to resolve a CDI managed bean by invoking it through an AnnotationLiteral:

@Inject
@Any
private Instance<FacesI18nService> services;

public FacesI18nService produceFacesServiceProgrammatically(Domain domain) {    
    return services.select(new DomainQualifier(domain)).get();
}

The DomainQualifier is just a standard AnnotationLiteral implementation:

public class DomainQualifier extends AnnotationLiteral<I18nResource> implements I18nResource {

    private static final long serialVersionUID = 1L;
    private final Domain domain;

    public DomainQualifier(Domain domain) {
        this.domain = domain;
    }

    @Override
    public Domain value() {
        return domain;
    }

}

The problem is that I do get a new FacesI18nService which is produced through the corresponding @Produces method. However, @Inject'd members of the FacesI18nService are always null

@Produces
@I18nResource
public FacesI18nService produceFacesService(InjectionPoint ip) {

    for (Annotation a : ip.getQualifiers()) {
        if (a instanceof I18nResource) {
            Domain domain = ((I18nResource) a).value();
            return new FacesI18nService(new I18nService(domain, databaseBundleService));
        }
    }
    throw new IllegalArgumentException("Could not find any matching qualifier");
}

So, what am I doing wrong here?

Upvotes: 3

Views: 979

Answers (1)

chzbrgla
chzbrgla

Reputation: 5188

Alright.. got it shame

In order to produce CDI managed beans, one should not instantiate the return value but rather pass it into the method as parameter and return this paramter as result.

@Produces
@Dependent
@I18nResource
public FacesI18nService produceFacesService(InjectionPoint ip, @New FacesI18nService ret) {

    [...]

    ret.setI18nService(new I18nService(domain, databaseBundleService));
    return ret;
}

Upvotes: 1

Related Questions