CDI作为工厂?

时间:2016-04-19 08:10:15

标签: java-ee cdi

我在JAX-RS Java EE应用程序上有这个端点:

public class SearchEndpoint implements ISearchEndpoint 
{

    @Inject protected SearchService searchService;

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

}

searchService's search方法中:

public class SearchService {

    @Inject private QueryVisitor visitor;

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

然后在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;
}

因此,CDI在我的JAX-RS端点实现上注入SearchService,然后CDI在先前注入的QueryVisitor中注入SearchService

所以,因为你能够基本上猜测QueryVisitor.visit充当工厂。根据{{​​1}}枚举值,它会创建一个EntityType对象。

我希望这些对象是使用CDI创建的。 我已经读过一些关于它的内容,但我还是无法弄清楚如何做到这一点。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

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

使用限定符?请尝试以下方法:

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