On 1/4/06, Laurie Harper <[EMAIL PROTECTED]> wrote: > > Craig McClanahan wrote: > > On 1/4/06, Garner, Shawn <[EMAIL PROTECTED]> wrote: > >> How do you get access to one managed bean from within another managed > >> bean? > >> > >> We have some business logic that depends on values in another managed. > > > > > > If you're trying to gain access from a class that extends > AbstractFacesBean > > or AbstractViewController, this is really simple: > > > > MyBean bean = (MyBean) getBean("name"); // "name" == managed bean > name > > of the other bean > > > > If you are in a class that doesn't extend one of these, it's a little > more > > work but still straightforward: > > > > FacesContext context = FacesContext.getCurrentInstance(); > > ValueBinding vb = context.getApplication > ().createValueBinding("#{name}"); > > MyBean bean = (MyBean) vb.getValue(context); > > > > Either of the above techniques will cause the other managed bean to be > > created, if it doesn't exist. If you *know* it exists, and what scope > it is > > in, you can also use the appropriate scoped map. Assume the other bean > is > > in session scope: > > > > FacesContext context = FacesContext.getCurrentInstance(); > > MyBean bean = (MyBean) context.getExternalContext > > ().getSessionMap().get("name"); > > > > Shawn > > > > > > Craig > > It's probably also worth pointing out that you could use 'dependency > injection' -- i.e. a managed property -- to supply the dependent bean > with its dependency, declaratively, through the faces-config.xml.
Good point ... that's even easier. Assume you have a managed bean named "business" that you want to inject into the backing bean containing your submit action. If that bean is called "myself", you would ensure that it has a public property that corresponds to the type of your business logic bean: public MyBean getBusinessBean() { ... } public void setBusinessBean(MyBean bean) { ... } and you'd configure it in faces-config.xml like this: <managed-bean> <managed-bean-name>myself</managed-bean-name> <managed-bean-class>com.mycompany.MyBackingBean</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> ... <managed-property> <property-name>businessBean</property-name> <value>#{business}</value> </managed-property> ... </managed-bean> Then, the business logic bean will get injected for you (created if necessary the first time) any time your backing bean is created. The only restriction is that you can't inject a bean from a shorter scope into a bean with a longer scope ... but that won't be an issue for something like this, because your page-oriented backing bean would typically have request scope, and the business logic bean would have application scope (if it was shared across all users), or perhaps the "none" scope to get a new instance every time. L. Craig