Global custom java objects

Enonic version: XP 6.10
OS: Centos 6


I try to invoke Java from Serverside JavaScript:

_var bean = _.newBean(‘com.test.JavaStuff’);
bean.method() etc…

As I know this will wrap the Java object in JavaScript object.
My questions are:
Is a new java object created each time?
I want to reuse the Java object across applications in Enonic XP, some kind of a global object created only once and reused again and again. How can I do that in Enonic XP?


A new Java object is created every time you call __.newBean(className).

You can create the object in a library and make it accessible with an exported function. The object will only be created the first time the library is required in the app. And it will be re-created every time the application is updated or restarted.


var bean = __.newBean('java.util.HashMap');

exports.getGlobalObject = function () {
    return bean;

Used in your controllers

var myLib = require('/lib/mylib');

var obj = myLib.getGlobalObject();

But this will not work across applications.
Reusing objects between applications is tricky, because you don’t have control over which applications are installed and running at any moment, and in which order they are initialised.
Why do you want to share objects between apps?

1 Like

All applications on my Enonic installation will use a java object that initializes a connection to Couchbase Server. Connection setup is expensive, that’s why I want to reuse the object to avoid connection leak.
But your answer is great. Reusing object at the application level is good enough for my use case.

Thank you.

1 Like

Technically, you should be able solve shared services between applications with “extensions” aka buiding your own OSGi bundles. However, this is not yet documented or officially supported for XP.