CDI compatible @ManagedProperty
In JSF 2.3, the built-in scope annotations are deprecated, there are some alternatives provided in CDI, eg. ApplicationScoped, SessionScope, RequestScoped, etc.
In JSF 2.2, JSF itself provided a CDI compatible ViewScoped, go here to view more details.
There is an exception, we can not find an alternative for the legacy @ManagedProperty, there is a useful blog entry describe how to created a CDI compatible @ManagedProperty from scratch.
Fortunately, JSF 2.3 provides a built-in CDI implementation.
Let's create a sample to try it.
Create a simple backing bean.
1
import javax.faces.annotation.ManagedProperty;
2
//...other imports
3
4
@Model
5
public class BackingBean {
6
7
@Inject
8
@ManagedProperty("#{fooBean.bar}")
9
private String message;
10
11
public String getMessage() {
12
return message;
13
}
14
15
public void setMessage(String message) {
16
this.message = message;
17
}
18
19
}
Copied!
NOTE, @ManagedProperty is from package javax.faces.annotation, which is newly added in JSF 2.3.
fooBean is a CDI bean, which has a property named bar.
1
@Named
2
public class FooBean {
3
4
private String bar = "bar from FooBean";
5
6
public String getBar() {
7
return bar;
8
}
9
10
public void setBar(String bar) {
11
this.bar = bar;
12
}
13
}
Copied!
In the facelets template, display the message of BackingBean.
1
<div>
2
CDI managed property: #{backingBean.message}
3
</div>
Copied!
Run this application on Glassfish v5, open your browser and navigate to http://localhost:8080/jsf-managedproperty/managedproperty.faces.
jsf cdi managedproperty
Grab the source codes from my GitHub account, and have a try.
Last modified 8mo ago
Copy link