简体   繁体   中英

How to inject config properties in Spring Boot to Spring Retry annotation?

In spring boot application, I define some config properties in yaml file as below.

my.app.maxAttempts = 10
my.app.backOffDelay = 500L

And an example bean

@ConfigurationProperties(prefix = "my.app")
public class ConfigProperties {
  private int maxAttempts;
  private long backOffDelay;

  public int getMaxAttempts() {
    return maxAttempts;
  }

  public void setMaxAttempts(int maxAttempts) {
    this.maxAttempts = maxAttempts;
  }

  public void setBackOffDelay(long backOffDelay) {
    this.backOffDelay = backOffDelay;
  }

  public long getBackOffDelay() {
    return backOffDelay;
  }

How can I inject the values of my.app.maxAttempts and my.app.backOffdelay to Spring Retry annotation? In the example below, I want to replace the value 10 of maxAttempts and 500L of backoff value with the corresponding references of config properties.

@Retryable(maxAttempts=10, include=TimeoutException.class, backoff=@Backoff(value = 500L))

Staring from spring-retry-1.2.0 we can use configurable properties in @Retryable annotation.

Use "maxAttemptsExpression", Refer the below code for usage,

 @Retryable(maxAttemptsExpression = "#{${my.app.maxAttempts}}",
 backoff = @Backoff(delayExpression = "#{${my.app. backOffDelay}}"))

It will not work if you use any version less than 1.2.0.Also you don't require any configurable property classes.

You can also use existing beans in expression attributes.

    @Retryable(include = RuntimeException.class,
           maxAttemptsExpression = "#{@retryProperties.getMaxAttempts()}",
           backoff = @Backoff(delayExpression = "#{@retryProperties.getBackOffInitialInterval()}",
                              maxDelayExpression = "#{@retryProperties.getBackOffMaxInterval" + "()}",
                              multiplierExpression = "#{@retryProperties.getBackOffIntervalMultiplier()}"))
    String perform();

    @Recover
    String recover(RuntimeException exception);

where

retryProperties

is your bean which holds retry related properties as in your case.

You can use Spring EL as shown below to load the properties:

@Retryable(maxAttempts="${my.app.maxAttempts}", 
  include=TimeoutException.class, 
  backoff=@Backoff(value ="${my.app.backOffDelay}"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM