Read an environment variable from applicationContext.xml

自作多情 提交于 2019-11-30 13:24:28

You can lookup JNDI entries (both environment entries and resources) with the JndiObjectFactoryBean or <jee:jndi-lookup>:

<jee:jndi-lookup id="PATH_ENV" jndi-name="PATH_ENV"/>

(To use the jee-namespace, you must declare it).

That defines a spring bean named "PATH_ENV" that contains (as a string) the path configured int the environment entry. You can now inject it into other beans:

<bean class="xy.Foo">
    <property name="path" ref="PATH_ENV"/>
</bean>

The remaining difficulty is concatenating the strings. (Unfortunately, there is no JndiPlaceholderConfigurer that would replace placeholders with JNDI environment entries, so you can't use the ${property}/foo syntax to concatenate, and must supply yet another bean definition:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <bean factory-bean="PATH_ENV" factory-method="concat">
            <constructor-arg>/myprop.properties</constructor-arg>
        </bean>
    </property>
</bean>

(code untested as I don't have a Spring project at hand to test it)

You can use context-param, that will work.

<context-param>
    <param-name>PATH_ENV</param-name>
    <param-value>C:/V3</param-value>
</context-param>

Why not just use the following?

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location" value="file:C:/V3/myprop.properties"/>
</bean>

I solved something, I think, similar.

I create a Windows System Variable with the changing part of the path:

my computer --> advanced options --> environment options --> Systeme Variable

And then with this I complete the path on Spring AppContext like this:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

   <property name="locations">  
       <list>
              <value>file:${PARENT_PATH}/conf/dev/jdbc.properties</value>
       <list>           
   </property>
</bean>

I don't know if really help, but for me works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!