Quick-n-Dirty: Use your own Factory classes in XPages

Here is a easy way to use your own factory classes in XPages:

1. Create a file named „com.ibm.xsp.factories.properties“ in the WEB-INF-Folder of your NSF

 

 

2. In this file, define the factory classes you want to use in the format<NAME>=<Java Class>

HelloWorldFactory=ch.hasselba.factory.HelloWorld

3. Create a java class, in this example ch.hasselba.factory.HelloWorld

package ch.hasselba.factory;

public class HelloWorld 
{
   public HelloWorld(){
      System.out.println("Hello World Factory alive!");
   }

   public String getMessage(){
      return "Hello World!";
   }

}

The factory classes you are adding require a constructor. They will be instantiated during runtime.

4. After saving your java class and opening a XPage you should see the message on the server console (perhaps you have to do a clean first).

This means that the Factory is now accessible and is ready to use. The class will only be instantiated once during runtime.

5. To use your Factory, you have to do a lookup first, before you can use it. This can be done using the com.ibm.xsp.factory.FactoryLookup class which can be accessed via the current application (Please read the notice in the ExtAPI documentation!).

Here is a SSJS code snippet:

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
   <xp:label id="labelHelloWorld">
      <xp:this.value>
         <![CDATA[#{javascript:
            var app = facesContext.getApplication();
            var facLookUp = app.getFactoryLookup();
            var hwFac = facLookUp.getFactory("HelloWorldFactory");
            hwFac.getMessage();
         }]]>
      </xp:this.value>
   </xp:label>
</xp:view>

The main difference between a managed bean and this approach is, that the class is instantiated as soon the JSF application starts running, not if you access the bean in your code for the first time. The factory class can do what you want, f.e. run a thread or whatever. The result of the operations can be accessed via the  factory lookup.

P.S. Keep in mind that this article has been posted in the „Quick-n-Dirty“ category.

Dieser Beitrag wurde unter Extensibility API, Java, JSF, Server, ServerSide JavaScript, XPages abgelegt und mit , , , , , , , verschlagwortet. Setze ein Lesezeichen auf den Permalink.

4 Antworten zu Quick-n-Dirty: Use your own Factory classes in XPages

  1. Nice one. And we all remember: Dirty stays long after Quick has gone!

  2. Man sagt:

    Sven,

    why dirty?, isn’t good stuff?

  3. Pingback: Quick-n-Dirty: Use your own Factory classes in XPages(2) – The VirtualPageTransformer | blog@hasselba.ch

Schreibe einen Kommentar zu Man Antworten abbrechen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.