i want to use 2 different beans (Spring) for one JSF-Page. I do not like to write every method into one bean, so i tried to separate into two beans like JobEditDataBean and JobEditActionBean.
I want to use the JobEdiDataBean just as “Container” for my data objects and move the actionstuff (like saving, update etc.) to the action bean.
What i did by now (and what seems to work, but feels wrong) is the following:
public class JobEditDataBean{
@Autowired
JobEditActionBean actionBean;
// some objects...
@PostConstruct
public void init() {
actionBean.setJobEditDataBean(this);
// do something ...
}
}
public class JobEditActionBean{
JobEditDataBean dataBean;
// some objects...
}
Do you have any hints or tipps how this can be done better, nicer?
Indeed, you don’t need to have one bean per each page. You can use as much beans you want for any page, it is fine, as whenever an expression like
#{someMB}is found in your XHTML, JSF will find a bean with that name and create a new instance if necessary.If you need to inject one bean to another, just use
@Autowiredalready:You just have to make sure both beans are in the Spring container (annotating them with
@Componentwill do), and choosing the right scope for each one. Beware of the scopes of the beans which you are injecting, cause it usually only makes sense to inject beans of broader scope to beans of the same or more restrict scope.Having said that, I recommend reading following thread about choosing the right scopes:
How to choose the right bean scope?
One more thing: this is only valid if your JSF beans are really being managed by the Spring container (that was my assumption after you used
@Autowired). If you are letting JSF container manage the beans (using@ManagedBeanwith@RequestScopedor@ViewScoped, for example), the way you inject them is with a@ManagedPropertyannotation: