0

I am trying to inject a named bean in another one. When I try to access properties of the injected bean , it returns null which means that the injection fails.

Here is the first Bean:

@Named
@SessionScoped
public class FirstMBean {

    String caracter;
      ..........

public String goToNext(){ 
String caracter=FacesContext.getCurrentInstance().getExternalContext().
                getRequestParame‌​terMap().get("caracter"); this.caracter=caracter;
 System.out.println("the selected caracteris"+ caracter);
 return "/pages/next?faces-redirect=true"; }

}

The second named bean:

@Named
@SessionScoped
public class SecondMBean {

    @Inject
    FirstMBean firstMBean ;
    String injectedCaracter ;


    @PostConstruct
    public void init() {

        this.injectedCaracter = this.firstMBean.getCaracter();
        System.out.println("injectedCaracter ----" + this.injectedCaracter);

    }

In my .xhtml page :

    <p:commandButton value="see caracter" action="#{firstMBean.goToNext}"> 
        <f:param name="caracter" value="#{caracter}" /> 
    </p:commandButton>

Please note that I am using tomcat server to which I added WELD to support CDI AND when I put the scope to ApplicationScoped, everything works fine.

Chouch
  • 63
  • 1
  • 1
  • 7
  • "When I try to access properties of the injected bean , it returns null which means that the injection fails.", is `firstMBean` null or `this.firstMBean.getCarater()`? – Smutje Apr 24 '15 at 11:51
  • @Smutje `this.firstMBean.getCaracter()` is null – Chouch Apr 24 '15 at 13:17
  • Well, then CDI works, because otherwise you would get a `NullPointerException`. Do you initialize `caracter` of `FirstMBean` somewhere? The default value for objects is `null`. – Smutje Apr 24 '15 at 15:18
  • Well you need to know when I put the scope to ApplicationScoped, everything works fine but it's not a solution – Chouch Apr 24 '15 at 15:26
  • So it's actually a scope problem - have you checked whether `caracter` is set *before* the `@PostConstruct` starts and grabs `caracter`? – Smutje Apr 24 '15 at 15:44
  • No it's not set because it gets its value when I press the commandButton – Chouch Apr 24 '15 at 16:30

0 Answers0