Injecting EJB 3 into Spring Bean

Michał Margiel picture Michał Margiel · Oct 18, 2012 · Viewed 7.5k times · Source

I am trying to inject EJB into Spring (3.1.2) service (both in different WARs) Both are very simple (methods removed to simplify example):

EJB:

@Remote
public interface MyBean {
}

@Singleton
public class MyBeanImpl implements MyBean{
}

Service:

@Service
public class MyServiceImpl implements MyService{
}

At first sight thing is very simple, but I tried:

@EJB(lookup = "java:global/ejbApp/MyBeanImpl!com.my.MyBean")
private MyBean myBean;

and it didin't work. Then I also tried:

@EJB(mappedName = "java:global/ejbApp/MyBeanImpl!com.my.MyBean")
private MyBean myBean;

And

@Resource(mappedName = "java:global/ejbApp/MyBeanImpl!com.my.MyBean")
private MyBean myBean;

but neither worked.

I managed to inject my EJB using:

<jee:jndi-lookup id="myBean" jndi-name="java:global/ejbApp/MyBeanImpl!com.my.MyBean" />

in my spring configuration and in the service:

@Autowired
private MyBean myBean;

But I really dont like this solution. I would like to have my JNDI path in some annotation to be able to do e.g:

@EJB(lookup = MyBean.JNDI_NAME)
private MyBean myBean;

Answer

Michał Margiel picture Michał Margiel · Oct 25, 2012

We have found quite nice and simple solution. Into spring configuration file one has to put:

<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor">
    <property name="alwaysUseJndiLookup" value="true" />
</bean>

And that enables spring to search for the beans annotated with @Resource in JNDI. So now one can do:

@Resource(mappedName = MyBean.JNDI_NAME)
private MyBean myBean;