【问题标题】:How to inject a properties file using Spring?如何使用 Spring 注入属性文件?
【发布时间】:2017-05-16 08:17:49
【问题描述】:

如何使用spring 直接将以下键值文件作为Properties 变量或HashMap 注入?

src/main/resources/myfile.properties:

key1=test
someotherkey=asd
(many other key-value pairs)

以下方法均无效:

@Value("${apikeys}")
private Properties keys;

@Resource(name = "apikeys")
private Properties keys;

旁注:我事先不知道属性文件中的键。所以我不能使用@PropertyResource注入。

【问题讨论】:

  • 您使用的是哪个春季版本?
  • spring-boot.1.5.3,因此是最新的spring 4
  • 不可能开箱即用(你需要一个单独的类来这样做)如果你想像你所做的那样声明它。但是如果你可以将它声明为StringpropertyMap= {key1:test, key2:test2},那么你可以使用SPEL直接映射到一个Map
  • @membersound @Value 是强制性要求吗?你会考虑使用@ConfigurationProperties吗?

标签: java spring


【解决方案1】:

您可以尝试实现此目的的一种方法是在您的配置文件中创建一个 bean:

@Bean
public Map<String, String> myFileProperties() {
    ResourceBundle bundle = ResourceBundle.getBundle("myfile");
    return bundle.keySet().stream()
            .collect(Collectors.toMap(key -> key, bundle::getString));
}

然后您可以轻松地将这个 bean 注入到您的服务中,例如

@Autowired
private Map<String, String> myFileProperties;

(考虑使用构造函数注入)

别忘了

@PropertySource("classpath:myfile.properties")

【讨论】:

    【解决方案2】:

    为了使用Value注解首先你需要在你的applicationContext.xml下面的bean中定义

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

    一旦你定义了你的属性文件,你就可以使用Value注解。

    【讨论】:

    • 我更喜欢基于注释的配置,因为 spring4 不再使用 xml 配置了。
    • 哦,好吧,抱歉没注意到,4.x 之前的版本可能还是有用的。
    【解决方案3】:

    你可以使用注解PropertySource:

    示例:

    @PropertySource("myfile.properties")
    public class Config {
    
        @Autowired
        private Environment env;
    
        @Bean
        ApplicationProperties appProperties() {
            ApplicationProperties bean = new ApplicationProperties();
            bean.setKey1(environment.getProperty("key1"));
            bean.setsomeotherkey(environment.getProperty("someotherkey"));
            return bean;
        }
    }
    

    【讨论】:

    • 不幸的是,这仅对静态值有用。 @membersound 在您回答属性文件中的键未知之后添加了一个编辑。
    猜你喜欢
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 2015-06-13
    • 2013-07-01
    • 2011-09-19
    相关资源
    最近更新 更多