-1

My web application crashes, when it reaches the constructor from my ProductsBean.

I get this error: Can't instantiate class: beans.ProductsBean

This is my ProductsBean:

@ManagedBean
@ViewScoped
public class ProductsBean implements Serializable {

    private List<ProductBean> products;

    @ManagedProperty(value = "#{applicationBean}")
    private ApplicationBean applicationBean;

    private ProductBean selectedProduct;


    public ProductsBean() {
        Store store = applicationBean.getStore();

        for (String c : store.getCategories()) {
            for (Product p : store.getProductsOfCategory(c)) {
                products.add(new ProductBean(p.getProduct_id(), p.getDescription(), p.getPrice(), p.getCategoryName()));
            }
        }

What is the cause of this error?

Alexey Gorozhanov
  • 706
  • 10
  • 20
user1939400
  • 51
  • 2
  • 9
  • Thanx, I will read some more tutorials. Do you also have a good tutorial with a ManagedBean for CRUD operations? – user1939400 Jan 04 '13 at 15:11

1 Answers1

3

applicationBean is null in the constructor.

When dealing with managed beans, leave the constructor as dumb as possible (and do not use managed properties there). The logic involve those should be in a @PostConstruct method, the framework will execute it after the managed properties have been updated.

@PostConstruct
private void init(){
  Store store = applicationBean.getStore();

  for (String c : store.getCategories()) {
    for (Product p : store.getProductsOfCategory(c)) {
      products.add(new ProductBean(p.getProduct_id(), p.getDescription(), p.getPrice(), p.getCategoryName()));
    }
  }
}

Also, you need the setter for the managed properties

public void setApplicationBean(ApplicationBean applicationBean) {
  this.applicationBean = applicationBean;
}
SJuan76
  • 24,532
  • 6
  • 47
  • 87