@Inject does not work inside annotated class @Scheduled

0

I'm creating a class using deltaspike and quartz, using @scheduled. In this Injection class a CDI bean, which is a class of service. I chose to use deltaspike because it controls the context of the CDI within classes that use quartz. The bean, however, is not injected, being null. No exception is thrown on the console. The code does not appear or be called. But removing all the code from the method, removing @Inject and leaving only the log calls, works perfectly. What might be missing configure for dependency injection to work? Follow the code below.

@Scheduled(cronExpression = "0 0/1 * * * ?")
public class NotificacaoAgendaJob implements Job {
    Logger logger = Logger.getLogger("br.com.nutrierp.scheduler");

    @Inject
    AgendaService agendaService;

    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            logger.info("Iniciando Job...");
            List<Agenda> agendas = agendaService.todasAgendasDoSistema();

            for (Agenda agenda : agendas) {
                LocalDateTime dataAgendada = agenda.getDataInicial();
                LocalDateTime dataAtual = LocalDateTime.now();
                Duration intervalo = Duration.between(dataAtual, dataAgendada);

                if (intervalo.toHours() <= 24 && intervalo.toHours() > 0) {
                    agendaService.enviarEmailDeNotificacao(agenda);
                }
            }
            logger.info("Finalizando Job...");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
    
asked by anonymous 07.03.2018 / 20:35

1 answer

0

After reading the deltaspike documentation again, I noticed that the beans are not injected because the annotated class with @scheduled is instantiated outside the context of the CDI. I used a CDIServiceLocator.

@Scheduled(cronExpression = "0 0 2 1/1 * ?")
public class NotificacaoAgendaJob implements Job {
    Logger logger = Logger.getLogger(NotificacaoAgendaJob.class.getName());

    SistemaService sistemaService;

    public void execute(JobExecutionContext context) {
        try {
            sistemaService = CDIServiceLocator.getBean(SistemaService.class);

            logger.info("Iniciando Job...");
            List<Agenda> agendas = sistemaService.todasAgendasDoSistema();

            for (Agenda agenda : agendas) {
                LocalDate dataAgendada = agenda.getDataInicial().toLocalDate();
                LocalDate dataAtual = LocalDateTime.now().toLocalDate();
                long intervalo = dataAgendada.toEpochDay() - dataAtual.toEpochDay();

                if (intervalo == 1) {
                    sistemaService.enviarEmailDeNotificacao(agenda);
                    logger.info("Enviando e-mail para " + agenda.getPaciente().getEmail());
                }
            }
            logger.info("Finalizando Job...");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

CDIServiceLocator

public class CDIServiceLocator {

    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clazz) {

        BeanManager bm = CDI.current().getBeanManager();

        Bean<T> bean = (Bean<T>) bm.getBeans(clazz).iterator().next();
        CreationalContext<T> ctx = bm.createCreationalContext(bean);
        T targetBean = (T) bm.getReference(bean, clazz, ctx);

        return targetBean;
    }

}

Console output

mar 08, 2018 9:44:00 PM br.com.nutrierp.scheduler.NotificacaoAgendaJob execute
INFORMAÇÕES: Iniciando Job...
Hibernate: select agenda0_.id as id1_0_, agenda0_.data_final as data_fin2_0_, agenda0_.data_inicial as data_ini3_0_, agenda0_.descricao as descrica4_0_, agenda0_.notificacao_agenda as notifica5_0_, agenda0_.notificacao_enviada_ao_agendar as notifica6_0_, agenda0_.notificacao_enviada_um_dia_antes as notifica7_0_, agenda0_.paciente_id as pacient10_0_, agenda0_.situacao as situacao8_0_, agenda0_.tipo as tipo9_0_, agenda0_.utilizador_id as utiliza11_0_ from agendas agenda0_ order by agenda0_.data_inicial desc
mar 08, 2018 9:44:07 PM br.com.nutrierp.scheduler.NotificacaoAgendaJob execute
INFORMAÇÕES: Enviando e-mail para [email protected]
mar 08, 2018 9:44:15 PM br.com.nutrierp.scheduler.NotificacaoAgendaJob execute
INFORMAÇÕES: Enviando e-mail para [email protected]
mar 08, 2018 9:44:22 PM br.com.nutrierp.scheduler.NotificacaoAgendaJob execute
INFORMAÇÕES: Enviando e-mail para [email protected]
mar 08, 2018 9:44:22 PM br.com.nutrierp.scheduler.NotificacaoAgendaJob execute
INFORMAÇÕES: Finalizando Job...

Using this CDIServiceLocator, all dependencies of all classes involved, including entity managers, will be resolved.

    
09.03.2018 / 01:52