Reputation: 141
I'm reading this book, Pro JPA2: Mastering the Java Persistance API, and I'm not getting the usefulness of the class-level annotation like in this example:
@EJB(name="cart", beanInterface=ShoppingCart.class)
public class ShoppingCartServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
//......
}
}
What's the point of putting that @EJB if the value of the cart variable won't be auto-injected in there and you have to init the var. yourself? Won't the code work just as well w/o that annotation? What does the annotation actually do?
I get the usefulness of the other type of annotations, like when you put it on the method or a variable, it'll auto-inject stuff. Just here, at the class level, it looks useless.
Upvotes: 3
Views: 1116
Reputation: 5327
class level @EJB (or @Resource) defines that your ShoppingCartServlet depends on some EJB, in your case "cart". You need that, if you want to access to EJBs from non-managed context, like POJOs. In this case, you have to make a JNDI look-up in order to get a reference to the EJB which you can define either with ejb-ref (ejb-local-ref) descriptor, or class level @EJB annotation.
Upvotes: 4
Reputation: 2737
That looks like a class level annotation rather than method level, and I have no idea why one would want to annotate a servlet as EJB, but the @EJB annotation when used properly will provide that class with many different things for free, such as transactions etc...
Upvotes: -1