Bill F
Bill F

Reputation: 2087

accessing a Java Bean from a different Java class

I have a Java Bean called appProps defined as an ApplicationScope that is a Hashmap and of the type <string, object>. I can access it via SSJS using the format

var appDesc:String = appProps["some application name"].getAppDesc();

and this returns the application description which is stored in one of the fields in the Hashmap Object.

Now I need to call the same process in another JAVA Class.

The definition in the faces-config is:

<managed-bean>
    <managed-bean-name>appProps</managed-bean-name>
    <managed-bean-class>ca.wfsystems.core.ApplicationMap</managed-bean-class>
    <managed-bean-scope>application</managed-bean-scope>
  </managed-bean>

Upvotes: 1

Views: 1711

Answers (3)

Georg Kastenhofer
Georg Kastenhofer

Reputation: 1417

Another (smart) way to access a java bean from a different java class

This is your bean class:

package ca.wfsystems.core;

import javax.faces.context.FacesContext;

public class ApplicationMap {

    // Constants

    private static final String BEAN_NAME = "appProps"; //$NON-NLS-1$

    // Operations

    public static ApplicationMap getCurrentInstance() {
        // This is a neat way to get a handle on the instance of this bean in the scope from other Java code...
        FacesContext context = FacesContext.getCurrentInstance(); 
        return (ApplicationMap) context.getApplication().getVariableResolver().resolveVariable(context, BEAN_NAME);
    }

}

And this one is a sample class using your bean class:

package ca.wfsystems.core;

public class ApplicationMapClient {

    // Operations

    public void doSomeThing() {

        ApplicationMap appMap = ApplicationMap.getCurrentInstance();
        // Your code goes here....

    }

}

For further information take a look at the blog entry a lesson on scoped managed beans in xpages from John Dalsgaard.

Upvotes: 0

Paul Stephen Withers
Paul Stephen Withers

Reputation: 15739

There are two easy solutions:

  1. ExtLibUtil.resolveVariable() allows you to access it by the variable name declared in faces-config, so appProps. ExtLib 14 allows you to just pass the name.

  2. Add a static get() method in the bean that uses ExtLibUtil.resolveVariable(). You can then call ApplicationMap.get()

Upvotes: 0

Jesse Gallagher
Jesse Gallagher

Reputation: 4471

The best Java equivalent of the implicit lookup that SSJS and EL do for appProps there is:

ApplicationMap appProps = (ApplicationMap)ExtLibUtil.resolveVariable(FacesContext.getCurrentInstance(), "appProps")

Upvotes: 1

Related Questions