0

I have a Quarkus app which runs a servlet and I'm trying to inject an Agroal datasource as there is a Thread which runs within the servlet where I need to do some database transactions. However, I've tried the below implementation inside the Thread class as well and another static class which is utilized inside the thread, but in both classes the datasource returns null.

I've added the datasource properties in the application.properties file as well. Also the servlet is set to load on startup, Hence as soon as the application is run, the thread starts as well. This thread starts after the servlet is initialized.

class LoopThread extends Thread {

@Inject @Named("db") AgroalDataSource datasource;

public LoopThread() { super();     }

@Override public void run() { try { DbUtil.userErrorLogged = false; DbUtil.initDataSource(datasource); LogUtil.debug("Thread started.");  

catch (Exception ex) { LogUtil.error(ex); }

} }

I have tried to inject the datasource in the Thread class and also in the static Util class but both did not return the datasource. I'm thinking whether it is due to the thread which is started as the servlet is initialized. Any help on this would be great

  • How are you creating an instance of the class? If you instantiate a class manually, `new LoopThread()`, dependency injection (as well as all other container services) can't work. – Ladicek Nov 21 '22 at 20:56
  • Yes that's how it is implemented. Is there a workaround I can do? – Vidath Adheesha Nov 22 '22 at 03:24
  • You can inject the datasource into the servlet (that is presumably managed by the container) and pass it around, or you can do programmatic lookup (`CDI.current().select(...)`). – Ladicek Nov 22 '22 at 08:33

0 Answers0