0

I am using Spring scheduling to schedule a task that performs some DB operation every hour. This throws a NullPointerException every time I try to call a function that triggers DB specific operations.

Configuration File :

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.bt.rtddashboard")
/*@EnableJpaRepositories(basePackages = {
        "com.bt.rtddashboard"
})*/
@EnableScheduling
@PropertySource("classpath:jdbc.properties")
public class RTDDashboardConfiguration extends WebMvcConfigurerAdapter {


    @Resource
    private Environment env;

    @Bean(name = "dataSource", destroyMethod="close")
    public DataSource getDataSource() {
        //DB code
    }

    private Properties getHibernateProperties() {
            //Hibernate code
    }

    @Bean(name = "sessionFactory")
    @Scope("singleton")
    public LocalSessionFactoryBean getSessionFactory() {

    }

    @Autowired
    @Bean(name = "transactionManager")
    public HibernateTransactionManager getHibernateTransactionManager(SessionFactory factory) {
    ;
    }

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("/").setCachePeriod(31556926);

    }

    @Scheduled(fixedRate=1000)
    public void work() {
        // task execution logic
        System.out.println("Scheduled Task");
        DashboardController controller=new DashboardController();
        controller.performTask();
    }

}

Dashboard Controller :

@RestController
public class DashboardController {

    @Autowired
    private InlineService service;

    @RequestMapping(value="/rtd/getAllServers", method=RequestMethod.GET)
    public ResponseEntity<List<ServerMonitor>> getAllServers(){
        List<ServerMonitor> ilsList=new ArrayList<ServerMonitor>();
        ResponseEntity<List<ServerMonitor>> response=null;

        try{
            ilsList=service.getAllServers();
            response=new ResponseEntity<List<ServerMonitor>>(ilsList,HttpStatus.OK);
            System.out.println("Scheduled Time");

        }catch(Exception e){

        }
        return response;
    }

public  void  performTask(){
        System.out.println("Scheduled Task Starts in Contrroller");
        List<IlsStats> ilsStats =new ArrayList<IlsStats>();
        List<IlsStatsHistory> ilsStatsHisList=new ArrayList<IlsStatsHistory>();
        try{
            //get All the ILS Stats
            ilsStats=service.getAllInlineStats();
            System.out.println("No of rows to Copy : " + ilsStats.size());
            ilsStatsHisList=formILSHistoryList(ilsStats);

            int flag=service.insertInIlsStatsHistory(ilsStatsHisList);

        //List<ServerMonitor> ilsList=service.getAllServers();

        }catch(Exception e){
            e.printStackTrace();
        }
    }

Here, ilsStats=service.getAllInlineStats(); throws NullPointerException.

Even though the rest webservice created on top of it is working fine.

Stack Trace :

Scheduled Task
Scheduled Task Starts in Contrroller
java.lang.NullPointerException
    at com.bt.rtddashboard.controller.DashboardController.performTask(DashboardController.java:226)
    at com.bt.rtddashboard.configuration.RTDDashboardConfiguration.work(RTDDashboardConfiguration.java:137)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65)
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

The same stack trace comes up every 1 sec now.

Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Jens Jul 11 '16 at 09:32
  • And you don't add the stack trace nor the actual beans it concerns... Please read http://stackoverflow.com/help/how-to-ask and improve your question after reading. – M. Deinum Jul 11 '16 at 09:33
  • @M.deinum My bad. This is the first time I am on this platform. I have added the stack trace and the controller code as well. – Rahul Agrawal Jul 11 '16 at 09:48
  • @Jens My issues is why I am getting this null pointer exception in scheduler function blocl alone while all the other rest web services that uses the same service object is working fine. – Rahul Agrawal Jul 11 '16 at 09:50
  • Maybe because the Service is not autowired? Which line you get the excpetion – Jens Jul 11 '16 at 10:11

1 Answers1

1

Creating an @Scheduled method in a configuration class is a very bad idea (imho). Next to that I also think that having a scheduler calling a controller method (a method tied to a web related component!) is generally a bad idea/design.

Nonetheless the problem is that you do new DashboardController(). That will obviously create a bean outside the scope of spring and will never be dependency injected. Instead inject the into the class and use that instance.

@Autowired
private DashboardController controller;

@Scheduled(fixedRate=1000)
public void work() {
    controller.performTask();
}

Or even better just remove that method all together and simply place @Scheduled(fixedRate=1000) on the performTask method instead.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224