【问题标题】:Spring Boot annotations: One PropertySource, many Properties?Spring Boot注解:一个PropertySource,多个Properties?
【发布时间】:2019-03-27 18:38:19
【问题描述】:

我正在尝试实现一个设置,其中单个 .properties 文件实际上被解析为多个 Properties 对象。

但没有任何变体组合(嵌套类、限定符等)实际上会产生相同的结果。

这甚至可能吗?这样做的推荐方法是什么?

下面的例子!

  // file: plugins.properties

  plugins.FooPlugin.enabled=true
  plugins.FooPlugin.amount=1
  plugins.BarPlugin.enabled=false
  // file: (...)/foo/Properties.java

  @Configuration
  @Qualifier("Foo Plugin Properties")
  @PropertySource("classpath:plugins.properties")
  @ConfigurationProperties(prefix = "plugins.foo-plugin")
  public class FooPluginProperties {
    boolean enabled;
    Integer amount; 
  }

  // file: (...)/bar/Properties.java

  @Configuration
  @Qualifier("Bar Plugin Properties")
  @PropertySource("classpath:plugins.properties")
  @ConfigurationProperties(prefix = "plugins.bar-plugin")
  public class BarPluginProperties {
    boolean enabled;
  }

我可能有点纠结于属性解析的魔力。

【问题讨论】:

  • 每个都有相同的属性?还是有些具有某些属性而有些具有其他属性?
  • 你可以删除这个@Qualifier("Bar Plugin Properties") spring根据类名创建bean,无论如何你有两个不同的类
  • 问题可能是@ConfigurationProperties(prefix = "plugins.foo-plugin")去掉- Spring使用一些宽松的规则来绑定属性和字段名
  • @just 每个插件可以有自己的 N 个属性
  • 我要做的是制作多个属性文件。如果它只是一个,我会创建一些解析器,从一个动态创建多个。

标签: java spring spring-boot properties


【解决方案1】:
@ConfigurationProperties(prefix="plugins")
public class FooBarProperties{
    @Value("${FooPlugin.enabled}")
    private boolean enabled;

    @Value("${FooPlugin.amount}")
    private Integer amount;

    @Value("${BarPlugin.enabled}")
    private boolean enabled;
}

如果你想要单独的类,只需将该栏插件移动到它自己的 pojo 中

当您需要属性时,只需自动装配您的类以注入值 即。

public void someFooBar() {
  @Autowired
  private FooBarProperties foobarProp;

...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 2020-06-09
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 2016-03-08
    相关资源
    最近更新 更多