How to annotate proxy beans to not be considered as "bean of interface" in CDI

51 views Asked by At

Following scenario

public interface MyInterface{
    
    void doSomething();
}

@ApplicationScoped
public static class MyInterfaceImpl implements MyInterface{

    @Override
    public void doSomething() {
        
    }
}


@ApplicationScoped
public static class MyInterfaceImplProxy implements MyInterface{

    @Inject
    MyInterface myInterface;
    
    @Override
    public void doSomething() {
        myInterface.doSomething();
    }
}

Of course, we now have a problem, as there are two beans available for one interface.

enter image description here

Is there a way to annotate the Proxy bean as such, so it won't be considered as an actual bean of type MyInterface or is the only way to use @Named beans here?

1

There are 1 answers

0
Siliarus On

You have two ways to go about this.

(1) You can start using CDI qualifiers to tell those beans apart - each bean has a set of type and set of qualifiers based on which it gets injected. In your example, default qualifiers are used, hence the ambiguous resolution.

(2) You can restrict bean types of a bean. This is done by placing @Typed() annotation on the bean class and explicitly listing the types you want that bean to have. Here is a link to the Jakarta doc describing it in more depth.

Last but not least, if you just meant to replace one impl with another one (or, in other words, provide an impl that should be prioritized), then you might want to look into CDI alternatives - which boils down to annotating the desired bean class with @Alternative @Priority(x). I am not sure this is what you are looking for, just putting it here so that you are aware of the option.