CDI freebies a.k.a built-in beans

Generally speaking,

The CDI programming model has pre-requisite 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

public class CDIFreebieResource {
UserTransaction uTx;
Principal actor;
HttpSession httpSession;
HttpServletRequest httpSR;
ServletContext sCtx;
public String get() throws Exception{
"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 …



About Abhishek

Loves Go, NoSQL DBs and messaging systems
This entry was posted in Java EE and tagged , , . Bookmark the permalink.

2 Responses to CDI freebies a.k.a built-in beans

  1. ondrejmihalyi says:

    Reblogged this on .Lost in Coding and commented:

    Life is plain simple with CDI injection…


  2. Pingback: CDI freebies a.k.a built-in beans | .Lost in Coding

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s