CDI Dependency Injection

Portlet 3.0 (see JSR 362) supports Contexts and Dependency Injection (CDI) so you can create and use injectable classes (CDI beans) in your portlet. It also provides injectable portlet artifacts called Portlet Predefined Beans. They give a portlet’s CDI beans access to the portlet configuration, preferences, requests, responses, and more. Here’s how to create and use CDI beans and Portlet Predefined Beans:

  1. Create a portlet WAR project, if you haven’t created one already.

    • Any project that has a class that implements the javax.portlet.Portlet interface, either directly or indirectly.
  2. If your portlet WAR project isn’t a Bean Portlet, add this src/main/webapp/WEB-INF/beans.xml file to it. This file tells CDI to scan the project for CDI annotations.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="" bean-discovery-mode="all" version="1.2"
    	<!-- This file is necessary in order to inform CDI that scanning should occur for CDI annotations. -->
  3. Add the @ApplicationScoped annotation to your portlet class.

    import javax.enterprise.context.ApplicationScoped;
    public class MyPortlet ... {
  4. Make sure all concrete classes you want to make injectable have the default constructor. These classes are now CDI beans.

  5. Add a scope to each CDI bean.

    Bean ScopeDescription
    @ApplicationScopedShares the bean’s state across all users’ interactions with the portlet.
    @Dependent(default scope) Designates the bean to be for the client bean and share the client bean’s lifecycle.
    @PortletRequestScopedAssociates the bean with the portlet request.
    @PortletSessionScopedPlaces the bean in the portlet session.
    @RenderStateScopedStores the bean as part of the portlet’s render state. Important: The bean must implement the PortletSerializable interface.
  6. Use the JSR 330 @Inject annotation in a CDI bean to inject another CDI bean into it. For example, this code informs Liferay DXP’s CDI bean container to inject a GuestBook CDI bean into this guestbook field.

    private GuestBook guestbook;
  7. Inject any Portlet Predefined Beans (portlet request scoped or dependent scoped beans) into your @PortletRequestScoped CDI beans.

    public class RequestProcessor ... {
        private PortletRequest portletRequest;
  8. Inject any dependent scoped Portlet Predefined Beans into your ApplicationScoped or @Dependent scoped CDI beans. For example,

    public class MyPortlet ... {
        private PortletConfig portletConfig;
  9. Use bean EL names to reference any portlet redefined named beans in your JSP or JSF pages.

  10. Deploy your project.

Congratulations! You have created and used CDI beans and Portlet Predefined Beans in your portlet.

CDI Portlet Predefined Beans


« Introduction to Dependency InjectionDeclarative Services »
¿Fue útil este artículo?
Usuarios a los que les pareció útil: 0 de 0