我正在做一个Spring Boot 2.1.6项目。
ScheduledTasks
当我有一个自动装配的对象时,我有了一个类,该对象db
可以让我访问jdbcTemplate
以便执行查询。当我start
从另一个文件main 调用from时,该db
对象为null。如果我start
直接将方法放在主类中,db
则该方法不为null。
我不确定是什么问题。我将@Component
注释放入其中,ScheduledTasks
以使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");
}
}
}
这是我的主要课程:
@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();
}
您正在ScheduledTasks
使用创建new
。在这种情况下,您将不会使用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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句