jakarta-eesession-bean

@Inject an interface in a session bean


I have a stateless session bean which does inject a interface from a library.

@Stateless
public class MyService {

    @Inject
    IMyLib iMyLib;
}

public interface IMyLib {
...
}

public class MyLib implements IMyLib {
...
}

This seams to work! But why? How could the container know what to inject?

Is this allowed and good practice?


Solution

  • It is good practice: using interfaces decouples your code from the implementation. It also allows multiple implementations which can be annotated with qualifiers so different uses of the code can use different implementations. It also allows decorators to add additional functionality.

    CDI documentation: What gets injected