mabn
mabn

Reputation: 2523

How to inject a value that can change at runtime?

There's a bunch (~100) of configuration parameters in the application. They can be manually adjusted at runtime through JMX (that's very rare). Their types vary, but usually these are simple types, date-time types from JodaTime, etc.

How it looks right now:

class Process {
    @Autowired
    private ConfigurationProvider config;

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

How I'd like it to look like:

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

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

If not possible, I could settle for (but I'd really prefer the previous one):

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

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

Is it possible? It would require re-injecting at runtime, but I'm not sure how to achieve that.

If it's not possible, what would be the closest alternative? I guess the other option is to inject some parameter wrapper, but would I need to define a bean for each parameter?

Upvotes: 0

Views: 716

Answers (1)

Ricardo Veguilla
Ricardo Veguilla

Reputation: 3155

Check Spring's JMX Integration. You should be able to do something like:

@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();
   }
}

However, if the configuration attributes are used in multiple beans, or if you usually modify more than one attribute at the same time, I think it is probably better to use your ConfigurationProvider as a @ManagedResource, to maintain the configuration centralized.

Upvotes: 1

Related Questions