2017-03-31 115 views
1

在spring引導應用程序中,我在yaml文件中定義了一些配置屬性,如下所示。如何將Spring Boot中的配置屬性注入到Spring Retry註釋中?

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春重試標註值是多少?在下面的示例中,我想將maxAttempts的值10和退避值的500L替換爲config屬性的相應引用。

@Retryable(maxAttempts=10, include=TimeoutException.class, [email protected](value = 500L)) 

回答

6

spring-retry-1.2.0盯着我們可以@Retryable註釋使用配置屬性。

使用「maxAttemptsExpression」,請參考下面的代碼使用,

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

,如果你使用任何版本少比1.2.0.Also你不需要任何配置屬性班,它不會起作用。

1

您可以使用Spring EL,如下圖所示加載性能:

@Retryable(maxAttempts="${my.app.maxAttempts}", 
    include=TimeoutException.class, 
    [email protected](value ="${my.app.backOffDelay}")) 
1

您還可以在表達式屬性中使用現有的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); 

其中

retryProperties

是你的bean持有重試相關屬性,如你的情況。

相關問題