Examples of Referencing Managed Bean Instances within other Managed Beans or POJO's


Example 1 - Define an instance getter on your Managed Bean class:

/*
 * @author Tony McGuckin, IBM
 */
public class AdminBean {

	public AdminBean(){}

	public static AdminBean get(FacesContext context) {
		return (AdminBean)context.getApplication().getVariableResolver().resolveVariable(context, "adminBean");
	}
	
	public static AdminBeanget() {
		return get(FacesContext.getCurrentInstance());
	}

	// any other methods etc specific to your bean... eg:
	public Boolean isDebug(){  return Boolean.TRUE; }
}

Then in some other Java class (either Managed Bean or POJO) you can obtain a handle to the bean instance like so:

public class MyClass {

	public MyClass(){
		if(AdminBean.get().isDebug()){
			System.out.println("Debug Mode On...");
			// doing some debug logging etc...
		}
	}

	// whatever else...
}



Example 2 - Use the Variable Resolver directly within a Managed Bean or POJO:

/*
 * @author Tony McGuckin, IBM
 */
public class MyOtherClass {

	public MyOtherClass() {
		FacesContext context = FacesContext.getCurrentInstance();
		AdminBean adminBean = (AdminBean)context.getApplication().getVariableResolver().resolveVariable(context, "adminBean");
		if(null != adminBean && adminBean.isDebug()){
			System.out.println("Debug Mode On...");
			// doing some debug logging etc...
		}
	}

	// whatever else...
}



Example 3 - Pass a reference to the Managed Bean of interest in method signatures.  Ensure the scope declared within the faces-config.xml for the Managed Bean is visible.

/*
 * @author Tony McGuckin, IBM
 */
public class MyOtherClass {

	public MyOtherClass(AdminBean adminBean) {
		if(null != adminBean && adminBean.isDebug()){
			System.out.println("Debug Mode On...");
			// doing some debug logging etc...
		}
	}

	// whatever else...
}
All code submitted to OpenNTF XSnippets, whether submitted as a "Snippet" or in the body of a Comment, is provided under the Apache License Version 2.0. See Terms of Use for full details.
No comments yetLogin first to comment...