3

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.

2 Answers 2

4

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.

2
  • Would ShoppingCart cart = (ShoppingCart) session.getAttribute("cart"); throw an exception if I didn't put @EJB annotation at the top of the class? Doesn't seem like it should.
    – Creature
    Oct 2, 2012 at 13:42
  • you have to still look-up card dependency using either initialcontext or sessioncontext since your class ShoppingCartServlet isnot managed. It doesn't work like Spring beans. Oct 2, 2012 at 13:55
-1

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...

1
  • Yeah, I mistyped the title of the post, sorry.
    – Creature
    Oct 2, 2012 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.