12

I am making a new Java webapp with Spring MVC 3.0 and want to use as much standard Java EE 6 stuff as I can. (I'm on Glassfish 3.1.1.) The real driver is wanting to use an MVC web framework rather than JSF.

So I'm looking for the best way to inject EJBs into my Spring controllers. I had some success but I'm not happy with how it looks and I was hoping to find a better way.

This worked, by finding the EJB via JNDI:

// EJB 
@Stateless
public class Service {
  @PersistenceContext(name="MAIN")
  private EntityManager em;

  public void doSomething() { .... } 

}

// Spring 
@Controller
public class HomeController {
   @EJB(mappedName="java:global/springtest/Service") 
   private Service service;

   // controller methods use service 
}

But I'm unhappy with needing the "mappedName" on the @EJB annotation in the controller.

Is there a better way to do this?

The good news, though, is that I can use the same @Inject annotation in EJBs and Spring beans and the only difference is which framework is creating the object and doing the injection.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
wrschneider
  • 17,913
  • 16
  • 96
  • 176

2 Answers2

2

If you use

mappedName="java:module/Service"

instead of

mappedName="java:global/springtest/Service"

you do not have to worry about the appname. This makes the code more portable. I guess that will solve some of your problems

Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
mabo
  • 56
  • 1
  • 5
-1

For Spring, you could wrap the JNDI lookup into JndiObjectFactoryBean:

<bean id="serviceBean" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:global/springtest/Service" />
    <property name="resourceRef" value="true" />
</bean>

Then you'll probably (correct me if I'm wrong) be able to use it with @Inject without the @Named("serviceBean") annotation:

@Inject
private Service service;
MaDa
  • 10,511
  • 9
  • 46
  • 84
  • That just pushes the problem to XML, which feels worse IMO. – wrschneider Oct 24 '11 at 13:40
  • @wrschneider99 Why? You wanted to get rid of the *mappedName* parameter and so you got it. Was not that the question? Otherwise you could do the JNDI lookup in the code and that would be fully portable, but ugly. – MaDa Oct 24 '11 at 14:11
  • I was hoping that there was some way that the JNDI lookup could happen by convention, such that an explicit mappedName was unnecessary. Or if necessary I wouldn't mind pushing the configuration to the Stateless annotation, to take advantage of any defaults inherent to Spring's interpretation of the EJB annotation. – wrschneider Oct 29 '11 at 21:01