自动装配不起作用,但手动创建对象有效

Autowired is not working but manually creating an object works

我试图在我的 class 中自动装配一个对象。没有错误或异常被抛出,但如果我调用它的方法,它就不会工作。我在这里错过了什么?

这就是我自动装配对象的方式:

    @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 class 的构造函数中添加 @Autowired。 您有多个构造函数,spring 不知道使用哪个构造函数来创建您的对象。

还应该有组件扫描注释,以便spring知道要扫描哪些包来查找组件。

@Configuration
@ComponentScan("com.your.package.withcomponents")
public class AppConfig{}

参考文献:

  1. Official Documentation
  2. Baeldung