Java 如何注入一个可以在运行时更改的值?
应用程序中有大量(~100)个配置参数。它们可以在运行时通过JMX手动调整(这是非常罕见的)。它们的类型各不相同,但通常是简单的类型,来自JodaTime的日期时间类型,等等 它现在的样子:Java 如何注入一个可以在运行时更改的值?,java,spring,configuration,dependency-injection,runtime,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 {
@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;
}
}
如果不可能,我可以满足(但我真的更喜欢前一个):
类进程{
@参数(Parameters.DELAY)
私有参数延迟;
公共无效doIt(){
int x=delay.get();
}
}
可能吗?这需要在运行时重新注入,但我不确定如何实现
如果不可能,最接近的替代方案是什么?我想另一个选项是注入一些参数包装器,但是我需要为每个参数定义一个bean吗?检查Spring的。您应该能够执行以下操作:
@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
,以集中维护配置
@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();
}
}