java 8 Springboot How to use properties from application.yml file in annotations?

huangapple go评论73阅读模式
英文:

java 8 Springboot How to use properties from application.yml file in annotations?

问题

<br/>
我使用的是Java 8,Spring Boot 2.2,并且有一段代码,其中我使用了`@Retryable`。截止目前,`backoff`和`maxattempt`字段是硬编码的,我希望能够使它们可配置。但是在这里,只允许使用常量;它们必须是final的。有没有办法克服这个问题?我记得在某个地方看到过一些代码,让我觉得这是可能的。我知道我可以通过`RetryTemplate`来实现。但我无法接受这样一个想法,即没有其他方法。
我想要这样做。

@Retryable(value = { SQLException.class }, maxAttempts = 2, backoff =
@Backoff(delay = 5000))

我希望它变成类似这样的形式

@Retryable(value = { SQLException.class }, maxAttempts =
"${applicationyml['myproperty']}", backoff = @Backoff(delay =
"${applicationyml['myproperty']}"))
英文:

<br/>
I am using java 8, Spring boot 2.2 and have a piece of code where I use @Retryable. The backoff, maxattempt fields as of now are hardcoded and I wish to make them configurable. But only constants are allowed in there; have to be final. Any idea on how to overcome this ? I remember seeing some code somewhere which makes me think its possible. I know I can do it via RetryTemplate. But I cant digest the idea that there is no other way.
I want this.

@Retryable( value = { SQLException.class },maxAttempts = 2,backoff =
@Backoff(delay = 5000))

I to become something like this

@Retryable( value = { SQLException.class },maxAttempts =
&quot;${applicationyml[&#39;myproperty&#39;]}&quot;,backoff = @Backoff(delay =
&quot;${applicationyml[&#39;myproperty&#39;]}&quot;))

答案1

得分: 2

使用 maxAttemptsExpression 等;

它们可以获取属性占位符 ${some.property},其中 some.property 在 YAML 中,或者使用 SpEL 表达式

#{@someBean.someProperty}

示例 在此处

@Retryable(exceptionExpression = &quot;#{@exceptionChecker.${retryMethod}(#root)}&quot;,
		maxAttemptsExpression = &quot;#{@integerFiveBean}&quot;, backoff = @Backoff(delayExpression = &quot;#{${one}}&quot;,
				maxDelayExpression = &quot;#{${five}}&quot;, multiplierExpression = &quot;#{${onePointOne}}&quot;))
public void service3() {
    ...
}
英文:

Use maxAttemptsExpression etc;

They can get property placeholders ${some.property} where some.property is in the YAML, or SpEL expressions

#{@someBean.someProperty}

Example here.

@Retryable(exceptionExpression = &quot;#{@exceptionChecker.${retryMethod}(#root)}&quot;,
		maxAttemptsExpression = &quot;#{@integerFiveBean}&quot;, backoff = @Backoff(delayExpression = &quot;#{${one}}&quot;,
				maxDelayExpression = &quot;#{${five}}&quot;, multiplierExpression = &quot;#{${onePointOne}}&quot;))
public void service3() {
    ...
}

huangapple
  • 本文由 发表于 2020年8月28日 03:13:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63622788.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定