Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View Scope in CDI Weld

I want to use the @ViewScoped - scope in my application for the backing beans of some web pages. Also I use CDI to inject the dependecies into the backing beans.

However, when I use a backing bean annotated like this

@ManagedBean
@ViewScoped

@Inject
someDependency (...)

the @Inject annotation will not inject anything and i get a NullPointerException as soon as i am accessing the dependency.

However, when I decorate the backing bean with

@Named
@ViewScoped


@Inject
someDependency (...)

the injection works fine, but now the @ViewScoped is ignored as it is not part of CDI / Weld.

How can I use @ViewScoped together with CDI Weld?

like image 645
Balu123 Avatar asked Feb 01 '11 16:02

Balu123


2 Answers

The problem is that you are mixing simple managed beans with CDI managed beans and they don't work together. Managed Beans is a simple framework for defining beans and their injected beans. CDI is a separate beast with all sorts of extra goodness.

However, Managed beans can't use CDI Injection points but can use the ViewScope while CDI beans use CDI injection points and all that good stuff but the ViewScope isn't available.

To resolve the issue you have to either go with CDI and use the Seam-Faces library to use view scope, or drop CDI and stick with simple managed beans which is a simple implementation.

Cheers,

Andy

like image 106
Andy Gibson Avatar answered Feb 19 '23 18:02

Andy Gibson


You can get @javax.faces.bean.ViewScoped to work by including the Seam Faces 3.1.0 jar in your project.

Failing that (i.e. you're using GlassFish 3.1.1 or earlier), you can simply copy ViewContextExtension.java, ViewScopedContext.java and javax.enterprise.inject.spi.Extension from Seam Faces 3.1.0 into your own project, ensuring you use the same path to the files as Seam Faces does. The java files can be copied verbatim. All lines except the one ending with ViewContextExtension should be removed from javax.enterprise.spi.Extension.

I am using the latter method successfully in GlassFish 3.1.1 and will try the former method one GlassFish 3.1.2 is released.

like image 29
Steve Avatar answered Feb 19 '23 18:02

Steve