我试图在我的类中自动连接一个对象。 没有抛出任何错误或异常,但是如果我调用该方法,它就不起作用。我在这里错过了什么?
这是我自动连接对象的方式:
@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 循环。依赖注入和手动创建对象有什么区别?
以下是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 不知道使用哪一个来创建您的对象。
还应该有组件扫描注释,以便 spring 知道要扫描哪些包来查找组件。
@Configuration
@ComponentScan("com.your.package.withcomponents")
public class AppConfig{}
引用:
- 官方文档
- 贝尔东