i have a backing bean managed by spring, and it’s scope is view
and i have a users page that display all users
and i want to pass to the datatable the list of users variable, and i want to initialize this variable on construction of the page (and use this variable as long as i am still in the page), and i am confused about the best way to initialize the list of users, i have 3 ways on my mind:
Initialize through constructor:
@Component("user")
@Scope("view")
public class MyBean {
private List<User> usersList;
public MyBean() {
usersList=userService.getUsers();
}
}
Initialize through preRender event:
@Component("user")
@Scope("view")
public class MyBean {
private List<User> usersList;
public void preRender(ComponentSystemEvent event){
if(usersList!=null)
usersList=userService.getUsers();
}
}
Initialize through @PostConstruct
@Component("user")
@Scope("view")
public class MyBean {
private List<User> usersList;
@PostConstruct
public void init() {
usersList=userService.getUsers();
}
}
please advise what is the best way for initialization in the case of view scope, i want to initialize the variable once, and use the exact same variable in the datatable as long as i am still in same page.
Initializing in constructor is only possible if the
userServiceis not an injected dependency. I.e. when you create it manually instead of using@EJB,@Injector@ManagedPropertyor whatever Spring specific.If the
userServiceis indeed an injected dependency, then the@PostConstructis the only right way, because the dependency is injected after construction and thus it would benullin the constructor.The
preRendermethod is called before every render response. It’s not called only once.