12 Replies Latest reply on Sep 17, 2010 12:37 AM by he youlin

    Inject a CDI class into JSF2 ManagedBean class

    Danilo Magrini Newbie
      Hi,

      I am trying to use @Inject annotation to inject MyClass in my JSF2 Managed beans.
      But i am getting NullPointerException. Any idea to fix this?

      @ManagedBean(name="ABC")
      @RequestScoped
      public class ABC {

      private @Inject MyClass my;

         public String loadDetails() {
             String aa = my.getXXX();   // NullPointerException
         }

      }


      import javax.enterprise.context.SessionScoped;
      import javax.inject.Named;

      @Named(value="myClass")
      @SesssionScope
      public class MyClass { ... }


      Thanks,
        • 1. Re: Inject a CDI class into JSF2 ManagedBean class
          Robert  Anderson Newbie

          Check if the package of @ManagedBean and @RequestScoped annotations in ABC class are correct (they exist in both specifications).

          • 2. Re: Inject a CDI class into JSF2 ManagedBean class
            Danilo Magrini Newbie
            Yes, they are.

            import javax.faces.bean.ManagedBean;
            import javax.faces.bean.RequestScoped;

            @ManagedBean(name="ABC")
            @RequestScoped
            public class ABC {

            private @Inject MyClass my;

               public String loadDetails() {
                   String aa = my.getXXX(); // NullPointerException
               }

            }
            • 3. Re: Inject a CDI class into JSF2 ManagedBean class
              Robert  Anderson Newbie

              No, they aren't. :)



              javax.annotation.ManagedBean;
              javax.enterprise.context.RequestScoped;


              Now, they are. ;)

              • 4. Re: Inject a CDI class into JSF2 ManagedBean class
                Danilo Magrini Newbie

                but I want my class ABC is like JSF2 type,..  because I want to use the ViewScoped.


                • 5. Re: Inject a CDI class into JSF2 ManagedBean class
                  Robert  Anderson Newbie

                  Sorry, but I think you have to use CDI ViewScoped or ConversationScoped.

                  • 6. Re: Inject a CDI class into JSF2 ManagedBean class
                    Jérémy Hérault Newbie

                    Hi,


                    I am currently facing this same problem. Have you found a solution? if it is, how did you and what are the necessary dependencies.


                    This a sample of what I'm trying to do (sorry to don't create my own topic but it's the same)


                    --AuthBean.java-- ManagedBean used in a .xhtml JSF2 file --------------------


                    import my.company.myproject.exceptions.AuthenticationException;

                    import javax.enterprise.context.RequestScoped;
                    import javax.faces.bean.ManagedBean;
                    import javax.inject.Inject;
                    import javax.inject.Named;
                    import javax.validation.constraints.Pattern;

                    @ManagedBean(name="authBean")
                    @RequestScoped
                    public class AuthBean{

                      @Pattern(regexp="(.+)", message="{constraint.invalid.name}")
                      private String login;

                      @Pattern(regexp="(.+)", message="{constraint.invalid.pwd}")
                      private String pwd;

                      @Inject @Named("authentication")
                      private IAuthentication iAuthentication;


                      public AuthBean(){}

                      public String authenticate(){
                        try{
                              if (iAuthentication.login(login, pwd)) //got a nullPointerException
                                forward = "login";

                            }catch(AuthenticationException e){

                                System.err.println(e.getMessage());
                            }

                            return forward;
                      }
                    }



                    --IAuthentication.java-- Interface used for authetication mechanism -----------


                    import my.company.myproject.exceptions.AuthenticationException;

                    public Interface IAuthentication{

                      public boolean login(String login, String pwd) throws AuthenticationException;

                    }


                    --AuthenticationImpl.java-- Implementation of the previous interface ----------


                    import my.company.myproject.exceptions.AuthenticationException;
                    import java.io.Serializable;
                    import javax.enterprise.context.SessionScoped;
                    import javax.inject.Named;

                    @Named("authentication")
                    @SessionScoped
                    public class AuthenticationImpl implements IAuthentication ,Serializable{

                      public AuthenticationImpl(){}

                      @Override
                      public boolean login(String login, String pwd) throws AuthenticationException {

                          boolean result = false;

                          if (login.equals("titi") && pwd.equals("toto")) result = true;

                          return result;
                      }
                    }


                    --content of my web page (.xhtml) calling my bean


                      <h:form id="authForm">  
                         <h:panelGrid columns="1">
                            <h:inputText id="login" value="#{authBean.login}"/>
                            <h:inputSecret id="pwd" value="#{authBean.pwd}"/>
                            <h:commandButton action="#{authBean.authentificate}" value="log in"/>
                         </h:panelGrid>          
                      </h:form>


                    ---------------------------------------------------------------------------



                    Hope I give you all the necessary information to help me.


                    Regards,

                    • 7. Re: Inject a CDI class into JSF2 ManagedBean class
                      Jérémy Hérault Newbie

                      _Jeremy Herault wrote on Sep 13, 2010 09:51:_<br/>

                      Hi,

                      I am currently facing this same problem. Have you found a solution? if it is, how did you and what are the necessary dependencies.

                      This a sample of what I'm trying to do (sorry to don't create my own topic but it's the same)

                      --AuthBean.java-- ManagedBean used in a .xhtml JSF2 file --------------------

                      import my.company.myproject.exceptions.AuthenticationException;

                      import javax.enterprise.context.RequestScoped;
                      import javax.faces.bean.ManagedBean;
                      import javax.inject.Inject;
                      import javax.inject.Named;
                      import javax.validation.constraints.Pattern;

                      @ManagedBean(name="authBean")
                      @RequestScoped
                      public class AuthBean{

                        @Pattern(regexp="(.+)", message="{constraint.invalid.name}")
                        private String login;

                        @Pattern(regexp="(.+)", message="{constraint.invalid.pwd}")
                        private String pwd;

                        @Inject @Named("authentication")
                        private IAuthentication iAuthentication;


                        public AuthBean(){}

                        public String authenticate(){
                          try{
                                if (iAuthentication.login(login, pwd)) //got a nullPointerException
                                  forward = "login";

                              }catch(AuthenticationException e){

                                  System.err.println(e.getMessage());
                              }

                              return forward;
                        }
                      }


                      --IAuthentication.java-- Interface used for authetication mechanism -----------

                      import my.company.myproject.exceptions.AuthenticationException;

                      public Interface IAuthentication{

                        public boolean login(String login, String pwd) throws AuthenticationException;

                      }

                      --AuthenticationImpl.java-- Implementation of the previous interface ----------

                      import my.company.myproject.exceptions.AuthenticationException;
                      import java.io.Serializable;
                      import javax.enterprise.context.SessionScoped;
                      import javax.inject.Named;

                      @Named("authentication")
                      @SessionScoped
                      public class AuthenticationImpl implements IAuthentication ,Serializable{

                        public AuthenticationImpl(){}

                        @Override
                        public boolean login(String login, String pwd) throws AuthenticationException {

                            boolean result = false;

                            if (login.equals("titi") && pwd.equals("toto")) result = true;

                            return result;
                        }
                      }

                      --content of my web page (.xhtml) calling my bean

                        <h:form id="authForm">  
                           <h:panelGrid columns="1">
                              <h:inputText id="login" value="#{authBean.login}"/>
                              <h:inputSecret id="pwd" value="#{authBean.pwd}"/>
                              <h:commandButton action="#{authBean.authentificate}" value="log in"/>
                           </h:panelGrid>          
                        </h:form>

                      ---------------------------------------------------------------------------


                      Hope I give you all the necessary information to help me.

                      Regards,
                      • 8. Re: Inject a CDI class into JSF2 ManagedBean class
                        Danilo Magrini Newbie

                        as Robert Anderson Nogueira said: Sorry, but I think you have to use CDI ViewScoped  or ConversationScoped.
                        and its true.

                        • 9. Re: Inject a CDI class into JSF2 ManagedBean class
                          Robert  Anderson Newbie

                          It works.


                          index.xhtml


                          <?xml version='1.0' encoding='UTF-8' ?>
                          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                          <html xmlns="http://www.w3.org/1999/xhtml"
                                xmlns:h="http://java.sun.com/jsf/html">
                              <h:head>
                                  <title>Facelet Title</title>
                              </h:head>
                              <h:body>
                                  <h:form id="authForm">
                                      <h:panelGrid columns="2">
                                          <h:outputLabel for="login" value="Login" />
                                          <h:inputText id="login" value="#{authBean.login}"/>
                                          <h:outputLabel for="pwd" value="Password" />
                                          <h:inputSecret id="pwd" value="#{authBean.pwd}"/>                
                                      </h:panelGrid>
                                      <h:commandButton action="#{authBean.authenticate}" value="log in"/>
                                  </h:form>
                              </h:body>
                          </html>
                          
                          



                          ok.xhtml


                          <?xml version='1.0' encoding='UTF-8' ?>
                          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                          <html xmlns="http://www.w3.org/1999/xhtml"
                                xmlns:h="http://java.sun.com/jsf/html">
                              <h:head>
                                  <title>Facelet Title</title>
                              </h:head>
                              <h:body>
                                  successfully login.
                              </h:body>
                          </html>
                          



                          AuthBean.java


                          package cditest;
                          
                          import javax.enterprise.context.RequestScoped;
                          import javax.inject.Inject;
                          import javax.inject.Named;
                          import javax.validation.constraints.Pattern;
                          
                          /**
                           *
                           * @author ranophoenix
                           */
                          @Named
                          @RequestScoped
                          public class AuthBean {
                          
                              @Pattern(regexp = "(.+)", message = "Login is invalid")
                              private String login;
                              @Pattern(regexp = "(.+)", message = "Password is invalid")
                              private String pwd;
                              @Inject
                              private IAuthentication iAuthentication;
                          
                              public AuthBean() {
                              }
                          
                              public String authenticate() {
                                  String forward = null;
                                  try {
                                      if (iAuthentication.login(getLogin(), getPwd())) {
                                          forward = "ok";
                                      }
                          
                                  } catch (AuthenticationException e) {
                                      System.err.println(e.getMessage());
                                  }
                          
                                  return forward;
                              }
                          
                              public String getLogin() {
                                  return login;
                              }
                          
                              public void setLogin(String login) {
                                  this.login = login;
                              }
                          
                              public String getPwd() {
                                  return pwd;
                              }
                          
                              public void setPwd(String pwd) {
                                  this.pwd = pwd;
                              }
                          
                          
                          }
                          



                          IAuthentication.java


                          package cditest;
                          
                          /**
                           *
                           * @author ranophoenix
                           */
                          public interface IAuthentication {
                          
                              public boolean login(String login, String pwd) throws AuthenticationException;
                          }
                          



                          AuthenticationImpl.java


                          package cditest;
                          
                          import java.io.Serializable;
                          import javax.enterprise.context.SessionScoped;
                          
                          /**
                           *
                           * @author ranophoenix
                           */
                          @SessionScoped
                          public class AuthenticationImpl implements IAuthentication, Serializable {
                          
                              public AuthenticationImpl() {
                              }
                          
                              @Override
                              public boolean login(String login, String pwd) throws AuthenticationException {
                          
                                  boolean result = false;
                          
                                  if (login.equals("titi") && pwd.equals("toto")) {
                                      result = true;
                                  }
                          
                                  return result;
                              }
                          }
                          



                          AuthenticationException.java


                          package cditest;
                          
                          /**
                           *
                           * @author ranophoenix
                           */
                          class AuthenticationException extends Exception {
                          
                          }
                          



                          /WEB-INF/beans.xml


                          <?xml version="1.0" encoding="UTF-8"?>
                          <beans xmlns="http://java.sun.com/xml/ns/javaee"
                                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
                          </beans>
                          



                          Regards,


                          Robert

                          • 10. Re: Inject a CDI class into JSF2 ManagedBean class
                            Jérémy Hérault Newbie

                            Great, it works. Really thank you for this little help.


                            Best regards,

                            • 11. Re: Inject a CDI class into JSF2 ManagedBean class
                              he youlin Novice

                              Can anybody create a jsf extensions like this?



                              import com.sun.faces.spi.InjectionProvider;
                              import com.sun.faces.spi.InjectionProviderException;
                              import com.sun.faces.vendor.WebContainerInjectionProvider;
                              public class JsfWeldInjectionProvider implements InjectionProvider {
                                      private static final WebContainerInjectionProvider con = new WebContainerInjectionProvider();
                                      private static JsfWeldInjector jsfWeldInjector=new JsfWeldInjector(ServletHelper.getModuleBeanManager((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext()));
                                      public void inject(Object managedBean) throws InjectionProviderException {
                                              con.inject(managedBean);
                                             
                                      }


                                      public void invokePostConstruct(Object managedBean)
                                                      throws InjectionProviderException {
                                              jsfWeldInjector.processAnnotations(managedBean);
                                              con.invokePostConstruct(managedBean);
                                             
                                      }


                                      public void invokePreDestroy(Object arg0) throws InjectionProviderException {
                                              // TODO Auto-generated method stub
                                             
                                      }
                                  private static class JsfWeldInjector extends AbstractInjector
                                  {


                                              protected JsfWeldInjector(WeldManager manager) {
                                                      super(manager);
                                                      // TODO Auto-generated constructor stub
                                              }
                                              public void processAnnotations(Object instance)
                                                {
                                                  this.inject(instance);
                                                }
                                  }
                              }



                              I don't test it.

                              • 12. Re: Inject a CDI class into JSF2 ManagedBean class
                                he youlin Novice
                                Can anybody create a jsf extensions like this? 
                                
                                import com.sun.faces.spi.InjectionProvider;
                                import com.sun.faces.spi.InjectionProviderException;
                                import com.sun.faces.vendor.WebContainerInjectionProvider;
                                public class JsfWeldInjectionProvider implements InjectionProvider {
                                     private static final WebContainerInjectionProvider con = new WebContainerInjectionProvider();
                                     private static JsfWeldInjector jsfWeldInjector=new JsfWeldInjector(ServletHelper.getModuleBeanManager((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext()));
                                     public void inject(Object managedBean) throws InjectionProviderException {
                                          con.inject(managedBean);
                                          
                                     }
                                
                                     public void invokePostConstruct(Object managedBean)
                                               throws InjectionProviderException {
                                          jsfWeldInjector.processAnnotations(managedBean);
                                          con.invokePostConstruct(managedBean);
                                          
                                     }
                                
                                     public void invokePreDestroy(Object arg0) throws InjectionProviderException {
                                          // TODO Auto-generated method stub
                                          
                                     }
                                    private static class JsfWeldInjector extends AbstractInjector
                                    {
                                
                                          protected JsfWeldInjector(WeldManager manager) {
                                               super(manager);
                                               // TODO Auto-generated constructor stub
                                          }
                                          public void processAnnotations(Object instance)
                                            {
                                              this.inject(instance);
                                            }
                                    }
                                }
                                
                                
                                I don't test it.