gpt4 book ai didi

java - 自动连线不起作用,但手动创建对象可以

转载 作者:太空宇宙 更新时间:2023-11-04 09:07:17 25 4
gpt4 key购买 nike

我试图在我的类中 Autowiring 一个对象。没有抛出错误或异常,但如果我调用其中的方法,它就不起作用。我在这里错过了什么?

这就是我 Autowiring 对象的方式:

    @Autowired
RetryOnException retry;

public static void main(String[] args) {
SpringApplication.run(CimsMigrationSftp100Application.class, args);
}

@Override
public void run(String... args) throws Exception {

while(retry.shouldRetry()) {
// More codes here and below
}

如果我使用RetryOnException retry = new RetryOnException();,它将起作用,并且我可以跳入while循环。依赖注入(inject)和手动创建对象有什么区别?

下面是RetryOnException():

import static package.PAUSE_MS;
import static package.POST_MAX_RETRIES;
@Component
public class RetryOnException {

private int numberOfRetries;
private int numberOfTriesLeft;
private long timeToWait;

public RetryOnException() {
this(POST_MAX_RETRIES, PAUSE_MS);
}

public RetryOnException(int numberOfRetries,
long timeToWait) {
this.numberOfRetries = numberOfRetries;
numberOfTriesLeft = numberOfRetries;
this.timeToWait = timeToWait;
}

/**
* @return true if there are tries left
*/
public boolean shouldRetry() {
return numberOfTriesLeft > 0;
}

public void errorOccured() throws Exception {
numberOfTriesLeft--;
if (!shouldRetry()) {
throw new Exception("Retry Failed: Total " + numberOfRetries
+ " attempts made at interval " + getTimeToWait()
+ "ms");
}
waitUntilNextTry();
}

public long getTimeToWait() {
return timeToWait;
}

private void waitUntilNextTry() {
try {
Thread.sleep(getTimeToWait());
} catch (InterruptedException ignored) {
}
}

}

最佳答案

尝试在RetryOnException类的构造函数中添加@Autowired。您有多个构造函数,而 spring 不知道使用哪一个来创建对象。

关于java - 自动连线不起作用,但手动创建对象可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60073475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com