Java – jsf2 applicationscope bean instantiation time?
In my opinion, the @ applicationscope bean starts only the first time you use el to access a page
Will the @ applicationscope bean be created when I query the applicationmap?
ExternalContext ec = currentInstance.getExternalContext(); result =
ec.getApplicationMap().get(beanName);
How to trigger instantiation of application scope beans before loading XHTML pages?
Solution
You can use eager = true in the @ managedbean declaration
@ManagedBean(eager=true)
@ApplicationScoped
public class Config {
// ...
}
In this way, the bean will be processed automatically when webapp starts
In addition, you can use application #evaluateexpressionget() to programmatically evaluate el to automatically create beans if necessary See also the example on this answer
FacesContext context = FacesContext.getCurrentInstance();
Confic config = (Config) context.getApplication().evaluateExpressionGet(context,"#{config}",Config.class);
// ...
You can also inject it as the @ managedproperty of the bean you need it for
@ManagedBean
@RequestScoped
public class Register {
@ManagedProperty("#{config}")
private Config config;
@postconstruct
public void init() {
// ...
}
// ...
}
JSF will automatically create the parent bean before injecting it It can be used in all methods except @ postconstruct
