java - 如何注入(inject)一个可以在运行时改变的值?

标签 java spring configuration dependency-injection runtime

应用程序中有一堆(~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();
    }
}

这可能吗?它需要在运行时重新注入(inject),但我不确定如何实现这一点。

如果不可能,最接近的替代方案是什么?我想另一个选择是注入(inject)一些参数包装器,但是我需要为每个参数定义一个 bean 吗?

最佳答案

检查 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,维护集中配置。

关于java - 如何注入(inject)一个可以在运行时改变的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25391806/

相关文章:

java - tomcat上的Spring Boot WAR文件部署显示错误404

当相机坐标与窗口坐标不匹配时,Java libGDX将不会绘制 Sprite

java - 多模块 Maven 项目中的 AOP 方面

linux - 如何实现这个功能呢? (这个功能的名字是什么?)

linux - Squid 最大 ips 数限制为 128

Objective-c 方法混淆在 DEBUG 中有效,但在 RELEASE 中崩溃

java - void 方法的单元测试和断言案例

java - 哪种数据结构用于存储矩阵对?

java - 创建名称为 'springSecurityFilterChain' 的 bean 时出错

java - 为什么垃圾收集器不破坏 Spring 容器