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.
Annotation for mapping web requests methods in the Spring MVC Controller. Both Spring MVC and Spring WebFlux support this annotation. @RequestMapping annotation provides several options to customize its behavior.
This annotation is simply a specialization of the @Component class and allows implementation classes to be autodetected through the classpath scanning. We can define a Spring MVC controller with @Controller. Read more at The Spring @Controller and @RestController Annotations with Examples
@ModelAttribute refers to a property of the Model object in Spring MVC. This ModelAttribute annotation binds a method parameter or method return value to a named model attribute, exposed to a web view. The annotation is used to define objects which should be part of a Model.
EJB - Annotations. Annotations were introduced in Java 5.0. The purpose of having annotations is to attach additional information in the class or a meta-data of a class within its source code. In EJB 3.0, annotations are used to describe configuration meta-data in EJB classes.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With