Search code examples
spring-bootautowiredservletcontextlistener

Spring Boot, Autowired is null in ServletContextListener.contextInitialized


I get a NullPointerException by Autowiring in contextInitialized, maybe somebody can help me, thanks a lot.

The Main class

@SpringBootApplication
@CompnentScan
public class Application extends SpringBootServletInitializer {
  public static void main(String[] args) throws Exception {
    SpringApplication.run(Application.class, args);
  }

  @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(Application.class);
  }

  @Bean
  public ProfileAdminListener profileAdminListener() {
    return new ProfileAdminListener();
  }
}

ServletContextListener

@WebListener()
public class ProfileAdminListener implements ServletContextListener {

private final Timer timer = new Timer();

public ProfileAdminListener() {
    setProperties();
}

private void setProperties() {
    ....
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
    timer.cancel();
    timer.purge();
}

@Override
public void contextInitialized(ServletContextEvent sce) {
    startProtokollTask();
}

private void startProtokollTask() {
    ProtokollFileWriteTask task = ProtokollFileWriteTask.getInstance();
    timer.schedule(task, 0, 10000);
}
}

Task

@Component
public class ProtokollFileWriteTask extends TimerTask {

private static ProtokollFileWriteTask instance = new ProtokollFileWriteTask();

@Autowired
private ProtokollService protokollService;

private ProtokollFileWriteTask() {
}

public static ProtokollFileWriteTask getInstance() {
    return instance;
}

@Override
public void run() {
    writeFile();
}

private void writeFile() {
    protokollService.writeProtokollFile("c:\temp");  <---- prtokollService is null
}
}

After start the appplication, I want to start the timetask, but I get a NullPointerException becuase the protokollservice is null. I think the service was not init before use it.

By use normal spring mvc xml config, this is no problem. How to config it by Spring boot? Thanks.


Solution

  • Kryger's anwswer is right, this problem is because I new a timetask, this is not controlled by spring. Thanks a lot.