【问题标题】:Get the values from the properties file at runtime based on the input - java Spring在运行时根据输入从属性文件中获取值 - java Spring
【发布时间】:2014-03-03 18:34:50
【问题描述】:

我的 colour.roperties 文件为

rose = red
lily = white
jasmine = pink

我需要获取颜色的值

String flower = runTimeFlower;
@Value("${flower}) String colour;

我们将在运行时获得的花卉值。我怎么能在java Spring中做到这一点。我需要在运行时根据用户输入获取单个值(从属性文件中定义的 50 个值中)。如果我不能使用 @Value ,您能告诉我其他处理方法吗?

【问题讨论】:

    标签: java spring properties-file


    【解决方案1】:

    @ike_love 说的是对的,但是为什么不在应用程序启动时将属性加载到内存中,然后您可以解决从地图中获取值的花?在我看来,您不需要将像这样的所有简单事情都委托给 Spring。无论如何我不知道你的 Spring 配置,但是为了让 Spring 能够加载你需要定义一个 PropertyPlaceholderConfigurer 来告诉属性文件在哪里的属性:

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

    【讨论】:

      【解决方案2】:

      Spring 从中读取的PropertySources 不知道flower 变量的值,因此@Value 将不起作用。

      注入Properties 对象或Map。然后分别使用属性名称或键查找颜色,例如

      <util:properties id="appProperties" location="classpath:app.properties" />
      
      ...
      
      @Autowired 
      @Qualifier("appProperties")
      private Properties appProperties;
      
      ...
      
      appProperties.getProperty(flower);
      

      【讨论】:

        【解决方案3】:

        没有办法使用@Value 来做你所描述的事情,但你可以这样做,这几乎是一回事:

        package com.acme.example;
        
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.core.env.Environment;
        import org.springframework.stereotype.Component;
        
        @Component
        public class Example {
            private @Autowired Environment environment;
        
            public String getFlowerColor(String runTimeFlower) {
                return environment.resolvePlaceholders("${" + runTimeFlower + "}");
            }
        }
        

        【讨论】:

        • 赞成作为一个有效的选项,尽管我试图避免在我的回答中与 Spring 如此紧密地绑定。我猜@user3147038 仍然需要学习投票和接受答案。 :)
        猜你喜欢
        • 1970-01-01
        • 2011-08-05
        • 1970-01-01
        • 1970-01-01
        • 2015-08-30
        • 2021-07-24
        • 2019-02-11
        • 1970-01-01
        相关资源
        最近更新 更多