Java EE – Handling EJB Exceptions with Multiple Implementations

dependency-injectioninterfacesjava-ee

In my JavaEE project I have an interface like this:

@Local
public interface DataAccess { ... }

And two stateless beans implementing it:

@Stateless
public class DataAccess_Online implements DataAccess { ... }

@Stateless
public class DataAccess_Offline implements DataAccess { ... }

And I get the exception:

Cannot resolve reference Local ejb-ref….
because there are 2 ejbs in the application with interface …DataAccess

The problem is clear, there may only be one class implementing DataAccess. But it would be convenient if I could use two. In the client I want to work on the Interface DataAccess only, so I donĀ“t have to distinguish between online/offline in my code, they both offer the same methods.

In the client I have an dependency injection:

@EJB
DataAccess da;

And I see how this is a problem with two implementations for DataAccess, but what should I change to make it work? The client always starts with the online version of DataAccess, but after a while he could request the offline version, so the offline version only needs the same interface, if I need a DataAccess injection it will always be the online version.

How can I use two implementations of an interface together with @EJB dependency injection?

Best Answer

You can use:

@Stateless(name="online")
public class DataAccess_Online implements DataAccess { ... }

@EJB(beanName="online")
DataAccess da;