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