Search code examples
javajakarta-eecdiweld

is it possible to create a bean using new() without making its inner beans unusable?


I'm using Weld for CDI. I'm looking for a way to run a periodic thread which includes injected beans.

In main i want to create:

executorService.scheduleWithFixedDelay(new ExampleThread(), 1, 1, TimeUnit.SECONDS);

where ExampleThread is:

@ApplicationScoped
public class ExampleThread implements Runnable {

    @Inject
    private SomeBean someBean;


    public ExampleThread() {}

    @Override
    public void run() {
        someBean.do();
    }
}

The issue is that once i create the ExampleThread using new() it makes its inner beans unusable. Is there a way to create the ExampleThread in a way that will work?


Solution

  • You can inject the bean this way:

    executorService.scheduleWithFixedDelay(new ExampleThread(), 1, 1, TimeUnit.SECONDS);
    

    and in the ExampleThread initialize the bean in the following way:

    public class ExampleThread implements Runnable
    {
        private SomeBean someBean;
    
        public ExampleThread()
        {
            this.someBean = CDI.current().select(SomeBean.class).get();
        }
    
        @Override
        public void run() {
            someBean.do();
        }
    }