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.
Nice one. And we all remember: Dirty stays long after Quick has gone!
Sven,
why dirty?, isn’t good stuff?
No, no! Good stuff 😉
I call this just „dirty“ because it is not an officially documented feature, no guarantee that this will work in future.
Pingback: Quick-n-Dirty: Use your own Factory classes in XPages(2) – The VirtualPageTransformer | blog@hasselba.ch