如何在Spring Boot中将配置属性注入Spring Retry注释?

mar*_*nzi 12 java spring spring-retry spring-boot

在spring启动应用程序中,我在yaml文件中定义了一些配置属性,如下所示.

my.app.maxAttempts = 10
my.app.backOffDelay = 500L
Run Code Online (Sandbox Code Playgroud)

还有一个例子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;
  }
Run Code Online (Sandbox Code Playgroud)

我怎么能注入的价值观my.app.maxAttemptsmy.app.backOffdelay对春重试注解?在下面的示例中,我想用配置属性的相应引用替换10maxAttempts和500Lbackoff值的值.

@Retryable(maxAttempts=10, include=TimeoutException.class, backoff=@Backoff(value = 500L))
Run Code Online (Sandbox Code Playgroud)

Vel*_*aga 19

spring-retry-1.2.0开始,我们可以在@Retryable注释中使用可配置属性.

使用"maxAttemptsExpression",请参阅以下代码以了解用法,

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

如果使用任何小于1.2.0的版本,它将无法工作.此外,您不需要任何可配置的属性类.


isa*_*mez 5

您还可以在表达式属性中使用现有的bean。

    @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);
Run Code Online (Sandbox Code Playgroud)

哪里

retryProperties

是您的bean,与您的情况一样,它保留与重试相关的属性。