-3

I'm doing a Spring Boot 2.1.6 project.

I have a class ScheduledTasks when I have an autowired object db which gives me access to jdbcTemplate so I can perform queries. When I call the start from main which is another file the db object is null. If I place the start method directly in main class db is not null.

I'm not sure what the issue is. I place @Component annotation in ScheduledTasks so that Spring is aware of my autowired object. What am I missing?

This is my 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");
        }
    }
}

this is my main 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();
    }
hitchhiker
  • 1,099
  • 5
  • 19
  • 44

1 Answers1

5

You are creating ScheduledTasks using new. In that case, you are not using an object created by spring hence auto-wire will not work. You should also wire the ScheduledTasks object in the main class.

@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();
    }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Amit Bera
  • 7,075
  • 1
  • 19
  • 42