You can't use @javax.faces.bean.ManagedProperty
in a CDI managed bean as annotated with @Named
. You can only use it in a JSF managed bean as annotated with @ManagedBean
.
You need use @javax.faces.annotation.ManagedProperty
instead, along with an @Inject
. This was introduced in JSF 2.3.
@Inject @javax.faces.annotation.ManagedProperty("#{msg}")
private ResourceBundle bundle;
Noted should be that this gets injected as a @Dependent
. So be aware that when you inject this into a @SessionScoped
bean, then it would basically become @SessionScoped
too and thus stick to the originally injected value forever. So any potential locale changes later on in the session won't be reflected there. If this is a blocker, then you should really inject it into a @RequestScoped
or @ViewScoped
only, or make use of a @Producer
as shown below.
CDI doesn't have native annotations to inject the evaluation result of an EL expression. The CDI approach is using a "CDI producer" with @Produces
wherein you return the concrete type, which is PropertyResourceBundle
in case of .properties
file based resource bundles.
So, if you cannot upgrade to JSF 2.3, then just drop this class somewhere in your WAR:
@RequestScoped
public class BundleProducer {
@Produces
public PropertyResourceBundle getBundle() {
FacesContext context = FacesContext.getCurrentInstance();
return context.getApplication().evaluateExpressionGet(context, "#{msg}", PropertyResourceBundle.class);
}
}
With this, can inject it as below:
@Inject
private PropertyResourceBundle bundle;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…