英文:
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 =
"${applicationyml['myproperty']}",backoff = @Backoff(delay =
"${applicationyml['myproperty']}"))
答案1
得分: 2
使用 maxAttemptsExpression
等;
它们可以获取属性占位符 ${some.property}
,其中 some.property
在 YAML 中,或者使用 SpEL 表达式
#{@someBean.someProperty}
示例 在此处。
@Retryable(exceptionExpression = "#{@exceptionChecker.${retryMethod}(#root)}",
maxAttemptsExpression = "#{@integerFiveBean}", backoff = @Backoff(delayExpression = "#{${one}}",
maxDelayExpression = "#{${five}}", multiplierExpression = "#{${onePointOne}}"))
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 = "#{@exceptionChecker.${retryMethod}(#root)}",
maxAttemptsExpression = "#{@integerFiveBean}", backoff = @Backoff(delayExpression = "#{${one}}",
maxDelayExpression = "#{${five}}", multiplierExpression = "#{${onePointOne}}"))
public void service3() {
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论