【问题标题】:Spring MVC @PropertySource all Key/value as a mapSpring MVC @PropertySource 所有键/值作为映射
【发布时间】:2015-08-14 00:41:51
【问题描述】:

在我的 Spring MVC 应用程序中,我想从指定的属性文件中读取 所有键/值。 我通过

将属性文件包含到我的 java 类中
@PropertySource("classpath:user-form-validation-configuration.properties")

并且可以一次读取一个键

@Autowired
Environment env;

env.getProperty("userIdEmail")

请帮助我如何将所有键/值作为 ma​​p

谢谢 手动

【问题讨论】:

    标签: java spring spring-mvc dictionary properties


    【解决方案1】:

    达到相同目的的一种方法是Spring: access all Environment properties as a Map or Properties object,其次是:

    <bean id="myProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
      <property name="location" value="classpath:user-form-validation-configuration.properties"/>
    </bean>
    

    对于,基于注释:

    @Bean(name = "myProperties")
    public static PropertiesFactoryBean mapper() {
            PropertiesFactoryBean bean = new PropertiesFactoryBean();
            bean.setLocation(new ClassPathResource(
                    "user-form-validation-configuration.properties"));
            return bean;
    }
    

    然后你可以在你的应用程序中选择它们:

    @Resource(name = "myProperties")
    private Map<String, String> myProperties;
    

    【讨论】:

    • 非常感谢 Arpit,第二个选项更简洁明了。但是我可以避免在 xml 文件中创建 bean。direct 可以在我的 Java 类中包含属性文件,或者带注释的类来加载属性文件.
    • 是的,在 jjava 中我可以配置 .@Bean(name="myProperties") public static PropertiesFactoryBean mapper() { PropertiesFactoryBean bean = new PropertiesFactoryBean(); bean.setLocation(new ClassPathResource("user-form-validation-configuration.properties"));回豆; }
    • 更新了帖子,基于注释。
    • @Manu:如果可行,请接受答案 - meta.stackexchange.com/questions/5234/…
    • @Manu 你应该接受有用的答案,这就是本网站的运作方式
    猜你喜欢
    • 2012-06-20
    • 2017-01-17
    • 2012-08-14
    • 2021-04-02
    • 2020-09-16
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多