当从另一个 class 调用使用它的方法时,为什么自动装配对象为空?

Why autowired object is null when the method using it is called from another class?

我正在做一个 Spring Boot 2.1.6 项目。

当我有一个自动装配的对象 db 时,我有一个 class ScheduledTasks,它使我可以访问 jdbcTemplate,因此我可以执行查询。当我从另一个文件 main 调用 start 时,db 对象为空。如果我直接将 start 方法放在 main class db is not null.

我不确定是什么问题。我在 ScheduledTasks 中放置 @Component 注释,以便 Spring 知道我的自动装配对象。我错过了什么?

这是我的 ScheduledTasks:

@Component
public class ScheduledTasks {
    private Logger log = VastLogger.getLogger(TrackingEventController.class);

    @Autowired
    private DBHandler db;

    public void start() {
        if (db == null) {
            log.info("db is null from parent");
        }
    }
}

这是我的主class:

@SpringBootApplication
@EnableJms
public class ServerMain implements CommandLineRunner {
    private static final Logger log = LogManager.getLogger(ServerMain.class);

    @Autowired
    private DBHandler db;

    public static void main(String[] args) {
        log.warn("from main");
        ConfigurableApplicationContext context = SpringApplication.run(ServerMain.class, args);

    }

    @Override
    public void run(String... strings) throws Exception {
        log.info("starting run");
        db.initDBTables();
        ScheduledTasks tasks = new ScheduledTasks();
        tasks.start();
    }

您正在使用 new 创建 ScheduledTasks。在这种情况下,您没有使用 spring 创建的对象,因此自动连接将不起作用。您还应该在主 class 中连接 ScheduledTasks 对象。

@SpringBootApplication
@EnableJms
public class ServerMain implements CommandLineRunner {
    private static final Logger log = LogManager.getLogger(ServerMain.class);

    @Autowired
    private DBHandler db;

    @Autowired
    private ScheduledTasks tasks;

    public static void main(String[] args) {
        log.warn("from main");
        ConfigurableApplicationContext context = SpringApplication.run(ServerMain.class, args);

    }

    @Override
    public void run(String... strings) throws Exception {
        log.info("starting run");
        db.initDBTables();
        tasks.start();
    }