【问题标题】:Is it possible to get an array of objects from Spring's application.properties?是否可以从 Spring 的 application.properties 中获取对象数组?
【发布时间】:2018-05-24 23:37:14
【问题描述】:

我知道我可以从properties 文件行属性创建对象。 我想要一个动态的对象数组,像这样。

application.properties

heroes.hero1=1,superman,kent
heroes.hero2=2,batman,wayne

假设某个时候有人会在文件中添加另一个英雄。 spring 是否可以自动理解对英雄数组的添加?这个问题有方法解决吗?还是更容易从 txt 文件中读取和构造此类对象。

【问题讨论】:

标签: java spring


【解决方案1】:

注入Environment并调用getProperty

import org.springframework.core.env.Environment;   

@Autowired
private Environment env;

public String[] getHero() {
   return env.getProperty("heroes",String[].class);
}

【讨论】:

    【解决方案2】:

    您实际上可以使用 Spring Boot 核心功能来实现这一点:

    例如创建一个新的 Java 类(现在将 Lombok 用于 Getters/Setters)

    @ConfigurationProperties(prefix = "heroes")
    @Getter
    @Setter
    public class HeroesProperties {
    
        private Map<String, List<String>> heroesMapping;
    
    }
    

    在您的 application.properties 中,您可以按照自己的方式动态添加更多英雄。

    例如

    • heroes.hero1=1,superman,kent
    • heroes.hero2=2,xx,aa
    • heroes.hero3=3,yy,bb
    • heroes.heroN=4,zz,cc

    【讨论】:

      【解决方案3】:

      是的,你可以。使用以下代码注入这些属性:

      @Value("${heroes.hero1}")
      private String[] heroes1;
      
      @Value("${heroes.hero2}")
      private String[] heroes2;
      

      【讨论】:

      • 我明白这一点。但是第二部分问了什么:Let's say that sometime somebody will add another hero to the file. Is it possible for spring to automatically understand additions to array of heroes?
      • 不,这是不可能的。这是属性,它们在引导时加载。你必须自己处理这个案子。
      • 它希望在不重启应用的情况下被识别。
      • 是的,但没关系。只要半专业用户可以更改属性并重新启动应用程序 - 我就可以了。他不需要深入研究代码。
      • 是的,我同意这一点。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 2019-03-28
      • 2014-04-07
      • 2013-04-02
      • 2011-01-03
      • 1970-01-01
      相关资源
      最近更新 更多