Creating an EJB3 Instance

I have some possible trivial questions.

If I defined an EJB3 + interface, let's say that it is removed like this:

@Remote public class FooServiceRemote { void foo(); } 

and one implementation

 @Stateless public class FooService implements FooServiceRemote { void foo() { ... } } 

How does the application server by default allow which implementation to use (and call through a proxy) if it knows only the @EJB annotation for dependency injection, for example, through the interface:

 public class SomeClass { @EJB private FooServiceRemote fooService; } 

Is this done by reflection (shortening the interface name)? Or he scans for possible implementations of such an interface, selecting it. Or..? And what if I want to create more implementations of one interface, is it possible and how to specify which implementation should be created (perhaps this is possible through some annotation argument).

Thanks: -)

+4
source share
2 answers

In the rare case, you need to have two beans that implement the same interface (not a good practice), you can name them and choose which one you want by name.

 @Stateless(name="FooService1") public class FooService1 implements FooService { } @Stateless(name="FooService2") public class FooService2 implements FooService { } public class SomeClass { @EJB(beanName="FooService1") private FooService fooService; } 

Other possible approaches look for it using the JNDI or the mappedName property. See Javadoc for EJB annotation here: http://download.oracle.com/javaee/6/api/javax/ejb/EJB.html

+4
source

Just fix

 @Remote interface FooServiceRemote { void foo(); } @Stateless public class FooService implements FooServiceRemote { void foo() { ... } } 

At the same time, the application server knows which classes implement the specified interface.

If you have two classes, you must specify which class you need.

+1
source

All Articles