Пружинный метод планирования cron4j, вызываемый до инициализации компонента
Я создал веб-приложение и запланировал работу cron с помощью cron4j. При выполнении cron вызывается метод run(), а в методе run() все остальные объекты bean-компонента имеют нулевое значение. Следовательно, я получаю NullPointerException. Ниже приведен мой пример кода.
class Employee {
@autowired IEmployeeService employeeService;
public void run() {
employeeService.getEmployeeDetails();
}}
В приведенном выше примере объект employeeService получает значение null и все другие объекты bean-компонента внутри getEmployeeDetails(); становятся нулевыми и getJdbcTemplate() также является нулевым.
Как инициализировать объекты bean весной при выполнении cron с помощью cron4j.
1 ответ
Вы можете использовать аннотацию @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.
Из весенней документации:
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/