【问题标题】:How to inject a value that can change at runtime?如何注入可以在运行时更改的值?
【发布时间】:2014-08-19 19:47:38
【问题描述】:

应用程序中有一堆(约 100 个)配置参数。它们可以在运行时通过 JMX 手动调整(这非常罕见)。它们的类型各不相同,但通常是简单类型、来自 JodaTime 的日期时间类型等。

现在的样子:

class Process {
    @Autowired
    private ConfigurationProvider config;

    public void doIt(){
        int x = config.intValue(Parameters.DELAY));
    }
}

我希望它是什么样子的:

class Process {
    @Parameter(Parameters.DELAY)
    private int delay;

    public void doIt(){
        int x = delay;
    }
}

如果不可能,我可以接受(但我更喜欢前一个):

class Process {
    @Parameter(Parameters.DELAY)
    private Param<Integer> delay;

    public void doIt(){
        int x = delay.get();
    }
}

有可能吗?它需要在运行时重新注入,但我不确定如何实现。

如果不可能,最接近的选择是什么?我猜另一种选择是注入一些参数包装器,但是我需要为每个参数定义一个 bean 吗?

【问题讨论】:

    标签: java spring configuration dependency-injection runtime


    【解决方案1】:

    查看 Spring 的 JMX Integration。您应该能够执行以下操作:

    @ManagedResource(objectName="bean:name=process", description="Process Bean")
    public class Process {
    
       private int delay;
    
       @ManagedAttribute(description="The delay attribute")
       public int getDelay() {
          return delay;
       }
    
       public void setDelay(int delay) {
          this.delay = delay;
       }
    
       public void doIt(){
          int x = getDelay();
       }
    }
    

    但是,如果配置属性在多个bean中使用,或者如果您通常同时修改多个属性,我认为将ConfigurationProvider用作@ManagedResource可能会更好,以维护配置集中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      相关资源
      最近更新 更多