javaspringtomcatjndicontext.xml

inject Property from jndi


My app uses spring, runs on tomcat

I have class

public class Entity{
    private String field;
    private Properties properties;

...geters/setters...
}

and context.xml

<?xml version='1.0' encoding='utf-8'?>
<Context>
    <Environment name="field.name" value="value" type="java.lang.String" override="false" />
</Context>

and spring.xml

...
    <bean id="entity" class="com.my.model.Entity">
        <property name="field">
            <jee:jndi-lookup jndi-name="java:comp/env/field.name" />
        </property>
        <property name="properties">
            <value>
                key1=value1
                key2=value2
                key3=value3
            </value>
        </property>
    </bean>
...

In which way I may inject values for Properties field via context.xml, such String field?


Solution

  • Context.xml cannot contain a Environment with a Map type. (The legal types are java.lang.Boolean, java.lang.Byte, java.lang.Character, java.lang.Double, java.lang.Float, java.lang.Integer, java.lang.Long, java.lang.Short, or java.lang.String)

    But you can include a property file in your deployment and reference that file's path via an Environment element. Then it is just a matter of injecting that property file's contents into your bean.

    <jee:jndi-lookup 
         id="beanConfigPath" 
         jndi-name="CONFIG_PATH"/>
    
    <bean ...>
        ...
        <util:properties id="properties" location="${beanConfigPath}" />
    </bean>