我使用cron4j构建了一个Web应用程序和预定的cron作业。在执行cron时,run()方法正在调用,而在run()方法中,所有其他bean对象都显示为null。因此,我得到NullPointerException。以下是我的示例代码。
班级员工{
@Autowired IEmployeeService employeeService;
public void run(){
employeeService.getEmployeeDetails();
} }
以上示例employeeService对象获取null以及getEmployeeDetails()中的所有其他bean对象;得到null并且getJdbcTemplate()也为null。
如何使用cron4j执行cron时在spring中初始化bean对象。
答案 0 :(得分:0)
您可以使用@BeanFactoryPostProcessor批注来命令bean的创建,并在bean初始化结束时创建/运行您的作业。
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.
来自Spring文档:
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.
请查找有关Spring文档的更多信息:http://docs.spring.io/spring/docs/4.1.3.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#beans-factory-extension-factory-postprocessors