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

23
在 Spring Boot 应用程序中,我在 yaml 文件中定义了一些配置属性,如下所示。
my.app.maxAttempts = 10
my.app.backOffDelay = 500L

还有一个茶豆的例子

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

我该如何将my.app.maxAttemptsmy.app.backOffdelay的值注入到Spring Retry注释中? 在下面的示例中,我希望使用配置属性对应的引用替换maxAttempts的值10和backoff值500L

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

29

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

使用"maxAttemptsExpression",参见下面的代码示例用法:

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

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


有没有办法只在yaml文件中设置属性,而不需要添加@Retryable注释?换句话说,上述内容是否有任何yaml配置属性? - Dchris
1
当我运行这个代码时,出现了 解析一个有效表达式后,表达式中仍有更多数据:'lcurly({)' 的错误提示。 - Baptiste Pernet
我遇到了同样的错误 - 表达式中仍然有更多数据:'lcurly({)' - Chandresh Mishra

13

您还可以在表达式属性中使用现有的 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);

where

retryProperties

是您的bean,其中包含与重试相关的属性,就像在您的情况下一样。


0
您可以使用如下所示的Spring EL来加载属性:
@Retryable(maxAttempts="${my.app.maxAttempts}", 
  include=TimeoutException.class, 
  backoff=@Backoff(value ="${my.app.backOffDelay}"))

7
你获得了一些赞,很奇怪,对我来说却出现了一个错误:“Error:(21, 27) java: incompatible types: java.lang.String cannot be converted to int”。看起来EL表达式没有被评估。 - Joel Mata

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接