地图的入口值取决于春天的环境变量

时间:2011-11-11 20:50:46

标签: java spring

我在应用程序上下文xml中有一个spring map声明,如下所示:

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

然而,价值永远不会被环境所取代。有没有办法做到这一点?

谢谢,

肖恩

2 个答案:

答案 0 :(得分:2)

如果您使用的是Spring 3

在Spring配置中,您可以使用SpEL,您需要的可能是systemProperties,如下所示:

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

答案 1 :(得分:2)

#{systemProperties}是否支持环境变量?什么是使用PropertyPlaceholderConfigurer(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

单元测试:

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"));
    }

}