简体   繁体   中英

How to set a property in class via Managed Bean?

I would like to set a property in my java class via the faces-config file:

<managed-bean>
    <managed-bean-name>utilsBean</managed-bean-name>
    <managed-bean-class>org.acme.bank.app.UtilsBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    <managed-property>
      <property-name>filePath</property-name>
      <value>#{javascript:@ReplaceSubstring(@LeftBack(database.getFilePath(),"\\"),"\\","/")+"/"}</value>
    </managed-property>
  </managed-bean>

On my UtilsBean class I have as property:

public String filePath;

and

public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

But when I output the value in the constructor I get a null value.

public UtilsBean() throws Exception {
        super();        
        Database database = ExtLibUtil.getCurrentDatabase();
        System.out.println("database.getFilePath() = " + database.getFilePath());//returns filepath of current nsf
        System.out.println("this filepath = " + this.filePath);//returns null


        try {
        ...
    }
}

To me it looks the property is not set via the faces-config or am I doing it the wrong way?

Over my progression through Java in XPages, I've come to the conclusion that lazy-loading is better. It's also one of the big advantages over SSJS because it's much easier in Java. So something like:

private String filePath; public void getFilePath() { if (null == filePath) { setFilePath(); } return filePath; } public void setFilePath() { filePath = getFilePathVariableInSomeWay(); }

This means you're calling the setting code once, only when it's used and not when the object is instantiated.

It also avoids calling SSJS, which is not as performant. It also means you can debug the setting code. It also means you're using a language-specific editor, with associated compiling validation, for generating the setting code. XML can't validate SSJS. A Java editor can ensure you don't have any compile-time errors.

I'm not sure of the benefits of using the faces-config for computing managed bean properties, to be honest I've never used them. But I can see some strong advantages of using methods in the Java class itself, whether in the constructor or the getter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM