Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Thinking in Java EE (At Least Trying To!)

DZone's Guide to

Thinking in Java EE (At Least Trying To!)

The CDI programming model isn't self-contained. But injecting the right beans will make it easier to think in Java EE. Here are a few.

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.


The CDI programming model has prerequisite requirements for beans which are lucky enough to leverage its services (DI, contextual state management etc.). This ranges from typical Java EE Managed Beans, EJB (session) beans etc. (I’ll leave the details for another post).

But the Good Thing is That

...it also provides some freebies i.e. beans which are available for injection by default

  • HttpSession
  • HttpServletRequest
  • ServletContext
  • UserTransaction
  • Principal

To be Noted

  • One can user either @Resource or the more obvious @Inject annotation to trigger injection
  • The @Default qualifier is applicable to injected instances of these beans
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
@Path("cdi/freebies")
public class CDIFreebieResource {

    @Inject
    UserTransaction uTx;
    @Inject
    Principal actor;
    @Inject
    HttpSession httpSession;
    @Inject
    HttpServletRequest httpSR;
    @Inject
    ServletContext sCtx;

    @GET
    public String get() throws Exception{
        return 
        "User Tx status: " + uTx.getStatus() + "\n" +
        "Principal: " + actor.getName() + "\n" +
        "HTTP Session ID: " + httpSession.getId() + "\n" +
        "HTTP Method: " + httpSR.getMethod() + "\n" + 
        "Context Path: " + sCtx.getContextPath();
    }
}

Where can I Inject These Beans ?

Well, standard rules (defined by the CDI specification) apply here. I would recommend looking into the official Java EE Platform specification document (section EE 5.2.5, Table EE.5-1) which details this clearly. Here is a snapshot – Java EE managed beans, CDI managed beans, EJB, Servlet spec components, Web Socket endpoints, JSF managed beans etc.

Go on, check out the freebies …

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
cdi ,java ,javaee

Published at DZone with permission of Abhishek Gupta, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}