Skip to content

Load self defined types as Beans or how to hook into the object creation process (New in 0.15.0)

Holger Thurow edited this page Mar 28, 2020 · 3 revisions

You can hook into Simple-JNDI's context and object creation process by implementing a javax.naming.spi.ObjectFactory as the following example shows:

package spi.objectfactories;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;
import java.util.Hashtable;

public class DemoBeanFactory implements ObjectFactory {

    @Override
    public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
        Reference ref = (Reference) obj;
        if (DemoBean.class.getName().equals(ref.getClassName())) {
            String fullName = (String) ref.get("fullName").getContent();
            int size = Integer.valueOf((String) ref.get("size").getContent());
            return new DemoBean(fullName, size);
        }
        else {
            return null;
        }
    }
}

To make this factory known to Simple-JNDI there are two ways:

The first one: Set in jndi.properties

java.naming.factory.object = spi.objectfactories.DemoBeanFactory

For the use of multiple factories separate them by a colon, e.g.

java.naming.factory.object = your.objectfactories.FirstObjectFactory:your.objectfactories.SecondObjectFactory

For the second one see Usage of 3rd party SPI ObjectFactory implementations (New in 0.21.0).

When made known by the first way the corresponding property file could look like

size = 186
fullName = Holger Thurow
type = spi.objectfactories.DemoBean

The example is taken from https://github.com/h-thurow/Simple-JNDI/tree/master/src/test/java/spi/objectfactories .

NEW in 0.22.0: object creation by SPI object factories is defered until lookup. So factories can depend on other JNDI objects.