RRoman
RRoman

Reputation: 751

Inconsistency with @ManagedProperty

i have a bean with a list of global data in @ApplicationScoped like this:

@ApplicationScoped
@ManagedBean
public class GlobalData
{
  private List data = new ArrayList();

  //getter and setterss goes here.. 

  public void addSomeData(Object item) { data.add(item); }
}

also i have a @ViewScoped bean that references GlobalData through a @ManagedProperty like this:

@ManagedBean
@ViewScoped
public class SomePageController
{
   @ManagedProperty(value="#{globalData}"
   private GlobalData theGlobalData;
   //also public getter and setter of theGlobalData
}

the funny thing comes when in SomePageController i want to add an item to the list of GlobalData like this:

public void someUIAction()
{
    SomeItem item = bussinesProcess();
    theGlobalData.addSomeData( item );
}

because each time someUIAction is called, theGlobalData points to a totally new instance with an empty data!!!! i can confirm this because i added some loggin info like this:

public void someUIAction()
{
    SomeItem item = bussinesProcess();
    theGlobalData.addSomeData( item );
    System.out.println(theGlobalData.toString());
}

and then i got the following output:

com.myproyect.beans.GlobalData@3c76da81
com.myproyect.beans.GlobalData@19c1818a
com.myproyect.beans.GlobalData@9a7jp79c
......

a new instance on every request, i googled but the only information i could get is with this guy with a similar problem, still i also tried he's solution with no luck =(.

** aditional info**: im developing with TomEE 1.5.2 web profile wich includes Apache MyFaces also i checked that all the anotations are from the javax.faces.bean package

Upvotes: 2

Views: 218

Answers (1)

BalusC
BalusC

Reputation: 1109162

That will happen if you have imported @ApplicationScoped annotation from the wrong package, such as CDI's javax.enterprise.context, which is what most IDEs suggest as 1st autocomplete option. As you're managing beans by JSF's @ManagedBean, then you need to make sure that you also use a managed bean scope from the same bean management API.

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

When a JSF managed bean doesn't have a valid annotation definied, then it defaults to @NoneScoped which is in this particular case indeed a brand new instance on every EL-resolution, such as @ManagedProperty.

Upvotes: 1

Related Questions