0
votes

we are using Glassfish, where we set JNDI resource of type Map, we define some Bean factory and after that we are able to access(JNDI lookup) this map in our code.

I would like to do the same for embedded Tomcat testing with Spring Boot, but I don'n know how. Everywhere they are just referencing how to add JNDI datasource not some Hashmap. I tried something like this, but my guess is it is completely wrong.

public TomcatEmbeddedServletContainerFactory tomcatFactory() {
     return new TomcatEmbeddedServletContainerFactory() {

        @Override
        protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
                Tomcat tomcat) {
            tomcat.enableNaming();
            return super.getTomcatEmbeddedServletContainer(tomcat);
        }
            @Override
            protected void postProcessContext(Context context) {
                ContextResource resource = new ContextResource();
                resource.setName("jndiname");
                resource.setType(Map.class.getName());
                // for testing only
                resource.setProperty("testproperty", "10");

                context.getNamingResources().addResource(resource);
            }
        };
    }


    @Bean(destroyMethod="")
    public Map jndiDataSource() throws IllegalArgumentException, NamingException {
        JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
        bean.setJndiName("jndiname");
        bean.setProxyInterface(Map.class);
        bean.setLookupOnStartup(false);
        bean.setResourceRef(true);
        bean.afterPropertiesSet();
        return (Map)bean.getObject();
    }

I'm don't know where to pass in the Object factory. Is it possible at all with the embedded Tomcat?

1

1 Answers

0
votes

The first thing to do is to create an ObjectFactory implementation that can return a Map:

public class MapObjectFactory implements ObjectFactory {

    @Override
    public Object getObjectInstance(Object obj, Name name,
            javax.naming.Context nameCtx, Hashtable<?, ?> environment)
            throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        // Configure the map as appropriate
        return map;
    }   
}

You then configure the ObjectFactory using the factory property on the ContextResource:

@Override
protected void postProcessContext(Context context) {
    ContextResource resource = new ContextResource();
    resource.setName("foo/myMap");
    resource.setType(Map.class.getName());
    resource.setProperty("factory", MapObjectFactory.class.getName());
    context.getNamingResources().addResource(resource);
}