Java 当从另一个类调用使用自动连线对象的方法时,为什么自动连线对象为null?
我正在做一个SpringBoot2.1.6项目 当我有一个自动连接的对象数据库时,我有一个类ScheduledTasks,它允许我访问jdbcTemplate,以便我可以执行查询。当我从另一个文件main调用start时,db对象为null。如果我将start方法直接放在主类中,db不为null 我不确定是什么问题。我将@Component注释放在ScheduledTasks中,以便Spring知道我的自动连线对象。我错过了什么 这是我的计划任务: 这是我的主要课程:Java 当从另一个类调用使用自动连线对象的方法时,为什么自动连线对象为null?,java,spring,spring-boot,autowired,Java,Spring,Spring Boot,Autowired,我正在做一个SpringBoot2.1.6项目 当我有一个自动连接的对象数据库时,我有一个类ScheduledTasks,它允许我访问jdbcTemplate,以便我可以执行查询。当我从另一个文件main调用start时,db对象为null。如果我将start方法直接放在主类中,db不为null 我不确定是什么问题。我将@Component注释放在ScheduledTasks中,以便Spring知道我的自动连线对象。我错过了什么 这是我的计划任务: 这是我的主要课程: @SpringBootAp
@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创建ScheduledTask。在这种情况下,您没有使用由spring创建的对象,因此“自动连线”将无法工作。您还应该连接主类中的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();
}
@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();
}