1

I have a Java Project with Spring MVC. I need to start TimerTasks already after my application is initialized, so I implemented the WebApplicationInitializer Interface and I call it SystemInitializer. Inside that class I have a @Autowired property, that @Autowired property is a DAO class. I need it cause I want to execute some tasks based in recordings from my data base. But that Autowired property is ever null.

public class SystemInitializer implements WebApplicationInitializer {

@Autowired
private DomainResearchDao domainResearchDao;

@Override
public void run() {
    if (this.domainResearchDao != null) {
        System.out.println("OK");
    }
    // always here
    else{
       System.out.println("NO OK");
    }
}
Bacteria
  • 8,406
  • 10
  • 50
  • 67
Andre
  • 652
  • 2
  • 7
  • 23

1 Answers1

1

You can not use @Autowired inside of WebApplicationInitializer.

Your Beans are not ready (not scanned yet) to be injected. Your Application has no idea what DomainResearchDao is at that moment.

Spring can autowire beans only after your application is initialized and all (singletone) instances (@Component, @Service etc.) are created.


If you want to do some job after your application is started, use Spring Event for doing this:

@Component
public class DoOnStart{

    @Autowired
    private IYourService service;

    @EventListener
    public void handleContextRefresh(ContextRefreshedEvent e) {
        // your CODE
    }

}

Just implement this class, no need to autowire it.

alex
  • 8,904
  • 6
  • 49
  • 75
  • Really? I didn't know that... So how can I do that? I need to start a service already after my application is initialized, but only once. If I put some code in a @Configuration class, it will be executed only once? Thanks – Andre May 29 '16 at 14:11