0
votes

I have build a web application and scheduled cron job using cron4j. While executing the cron the run() method is calling and in the run() method all other bean objects are showing null. Hence, I am getting NullPointerException. Below is my sample code.

class Employee{

@autowired IEmployeeService employeeService;

public void run() {

employeeService.getEmployeeDetails();

} }

The above example employeeService object getting null and all other bean objects inside getEmployeeDetails(); are getting null and getJdbcTemplate() is also null.

How to initialize bean objects in spring while executing cron using cron4j.

1

1 Answers

0
votes

You can use @BeanFactoryPostProcessor annotation to order creation of beans and create/run your job at the end of bean initialization.

The definition of BeanFactoryPostProcessor to bean (configuration metadata) processing. That is to say, the Spring IoC container allows configuration of BeanFactoryPostProcessor metadata in the container before the actual read instantiate any other bean, and may modify it. If you want, you can configure multiple BeanFactoryPostProcessor. You can control the BeanFactoryPostProcessor by setting the'order'attribute of the execution order.

From Spring documentation:

The next extension point that we will look at is the org.springframework.beans.factory.config.BeanFactoryPostProcessor. The semantics of this interface are similar to those of the BeanPostProcessor, with one major difference: BeanFactoryPostProcessor operates on the bean configuration metadata; that is, the Spring IoC container allows a BeanFactoryPostProcessor to read the configuration metadata and potentially change it before the container instantiates any beans other than BeanFactoryPostProcessors.

Please find more information on Spring docs: http://docs.spring.io/spring/docs/4.1.3.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#beans-factory-extension-factory-postprocessors