@Inject does not work inside annotated class @Scheduled

Asked

Viewed 168 times

0

I am creating a class using deltaspike and Quartz, using @scheduled. In this class I inject a CDI bean, which is a service class. I chose to use deltaspike because it controls the CDI context within the classes that use Uartz. The bean, however, is not injected and is null. No exception is fired on the console. The execute code does not appear to be called. But by taking all the code out of the method, removing @Inject and leaving only the log calls, it works perfectly. What may be missing to set up for dependency injection to work? Follow code.

@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();
        }
    }

}
  • Where is the rest of the code, the code of web.xml, springContext.xml?

  • Weslley, in the deltaspike documentation there is no reference to additional configurations in web.xml, nor required configurations in Quartz.proprties. in fact, without including @Inject and removing the code that uses the injected object, the execute method runs. My application does not use spring, CDI only

  • And if the Agendaservice class ? Vc added @Named ?

  • Normally for a dependency to be created, you add @named, I think the Notificaoagendajob class is not a bean so it does not load the Agendaservice

1 answer

0

After reading the deltaspike documentation again, I noticed that the Beans are not injected because the class annotated with @scheduled is instantiated outside the CDI context. 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.