Jordi
Jordi

Reputation: 23207

CDI as a factory?

I have this endpoint on my JAX-RS Java EE application:

public class SearchEndpoint implements ISearchEndpoint 
{

    @Inject protected SearchService searchService;

    @Override
    public Response search()
    {
        return Response.ok().entity(this.searchService.search()).build();
    }

}

In searchService's search method:

public class SearchService {

    @Inject private QueryVisitor visitor;

    public List<?> search() {
        for (Expression<?> group : groups)
            group.accept(this.visitor);
    }
}

And then in QueryVisitor,

@Override
public ESEntityPathPointer<?> visit(Expression<?> expr, ESEntityPathPointer<?> context) {
    switch ((EntityType)expr.getMetadata().getElement())
    {
        case digitalInput:
            if (context == null)
                context = new DigitalInputESEntityPathPointer();
            break;
        case followUpActivity:
            if (context == null)
                context = new FollowUpActivityESEntityPathPointer();
            break;
        case ...;
    }
    return context;
}

So, CDI injects a SearchService on my JAX-RS endpoint implementation, then CDI injects a QueryVisitor in previously injected SearchService.

So, As you're able to guess basicly QueryVisitor.visit acts as a factory. According to a EntityType enum value it creates an ESEntityPathPointer<?> object or another.

I'd like these objects are created using CDI. I've read a bit about it, nevertheless I'm not quite able to figure out how to do this.

Any ideas?

Upvotes: 0

Views: 285

Answers (1)

cassiomolin
cassiomolin

Reputation: 130887

Try the following:

SomeBean bean = CDI.current().select(SomeBean.class).get();

Using qualifiers? Try the following:

SomeBean bean = CDI.current().select(SomeBean, 
                                     new AnnotationLiteral<Qualifier1>(){}, 
                                     new AnnotationLiteral<Qualifier2>(){}).get();

Upvotes: 1

Related Questions