Reputation: 225
Is it possible to use events in Spring Boot? I need to execute one method but without waiting for return. I'm trying to use this:
public class GerarSeloEvent extends ApplicationEvent {
private TbPedido pedido;
private Integer cdCartorio;
public GerarSeloEvent(Object source, TbPedido pedido, Integer cdCartorio) {
super(source);
this.pedido = pedido;
this.cdCartorio = cdCartorio;
}
public TbPedido getPedido() {
return pedido;
}
public Integer getCdCartorio() {
return cdCartorio;
}
}
@Component
public class GerarSeloListener implements ApplicationListener<GerarSeloEvent> {
@Autowired
SeloService seloService;
@Override
public void onApplicationEvent(GerarSeloEvent event) {
seloService.gerarSelos(event.getPedido(), event.getCdCartorio());
}
}
and my call
GerarSeloEvent gerarSelos = new GerarSeloEvent(this, pedido, cdCartorio);
EnviarEmailPedidoEvent enviarEmail = new EnviarEmailPedidoEvent(this, pedido);
publisher.publishEvent(gerarSelos);
But my code waits to return anything to my front-end. I need one async event.
Upvotes: 1
Views: 4591
Reputation: 33091
This should work:
@Component
public class GerarSeloListener {
private final SeloService seloService;
@Autowired
public GerarSeloListener(SeloService seloService) { ... }
@EventListener
@Async
public void handleGerarSeloEvent(GerarSeloEvent event event) {
....
}
You need to add @EnableAsync
on one of your configuration (the best place is your @SpringBootApplication
annotated class). But as Martin already said you don't need event if you want to process a method asynchronously: only add @Async
and invoke it the usual way.
You may want to read the documentation
Upvotes: 4