EJB 3.0 Injecting The Correct Implementation

When using stateless and stateful session beans I often find that I’m creating one interface per one implementation, which will be enhanced with the release of the 3.1 spec and implicit interfaces. Anyway on one of the occasions I had actually had multiple implementations of an interface that I wanted to inject, this made me stop and think how do I that!! It turns out it was pretty simple with a few annotations.

On your class that is implementing the interface you need to use the name attribute: –


@Stateful(name="xxx.AssetTypeOverrideService")
public class AssetTypeOverrideService implements OverrideService{

@Stateful(name="xxxRuleTypeOverrideService")
public class RuleTypeOverrideService implements OverrideService {

Then on the bean you want inject these into you use:


@EJB(beanName="xxx.AssetTypeOverrideService")
private OverrideService assetOverrideService;
	
@EJB(beanName="xxx.RuleTypeOverrideService")
private OverrideService ruleTypeOverrideService;

The name can be anything you want I just think it’s logical to keep it the same as the class and the beanName obviously is the same value of the bean you want to inject that has the correct implementation.

It seems easy now but it did make me stop and think.

Advertisements