Sean Nguyen
Sean Nguyen

Reputation: 13158

entry value of a map depends on environment variable in spring

I have a spring map declare in the application context xml like this:

<map>
    <entry key="mykey">
       <value>${${env}.userkey}</value>
    </entry> 
</map>

However the value never be substituted by the environment. Is there a way to do this?

Thanks,

Sean

Upvotes: 1

Views: 1619

Answers (2)

szhem
szhem

Reputation: 4712

Does #{systemProperties} support environment variables? What's about using PropertyPlaceholderConfigurer which does (link)

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
">

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:env.properties" />
</bean>

<util:map id="map">
    <entry key="mykey">
       <value>${${env}.userkey}</value>
    </entry>
</util:map>

env.properties:

local.userkey=Me

Unit test:

package org.test;

import static org.junit.Assert.assertEquals;
import java.util.Map;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class EnvTest {

    @Resource
    private Map<String, String> map;

    @Test
    public void testMap() throws Exception {
        assertEquals("Me", map.get("mykey"));
    }

}

Upvotes: 2

Adam Jurczyk
Adam Jurczyk

Reputation: 2131

If you are using Spring 3

In Spring configs you can use SpEL, and what you need is probably systemProperties like this:

<map>
    <entry key="mkey" value="#{ systemProperties['env'] + '.userkey' }" />
</map>

Upvotes: 2

Related Questions