Search code examples
jakarta-eeejbjava-ee-6ejb-3.1java-ee-7

How can a singleton Java EE bean obtain a reference to itself?


I have a singleton bean for which the @PostConstruct method needs to call an @Asynchronous method within itself. It cannot do so directly using this because that makes the call synchronous. I cannot @Inject itself because it is circular.


Solution

  • You can use such type of wrapper:

    @Singleton
    public class SingletonBean {
    
    
    
    @Stateless
    public static class AsynchronousMethodLauncher{
        @EJB
        private SingletonBean singletonBean;
    
        public void launch(){
            singletonBean.asynchronousMethod();
        }
    }
    
        @EJB
        AsynchronousMethodLauncher launcher;
    
        @Asynchronous
        public void asynchronousMethod(){
            //Place your code here
        }
    
        public void yourMethod(){
            launcher.launch();
        }
    }