0

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.

necromancer
  • 23,916
  • 22
  • 68
  • 115

2 Answers2

5

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();
    }
}
gluckonavt
  • 236
  • 1
  • 4
  • good suggestion! (if a better answer is posted i will accept it) – necromancer May 12 '13 at 08:03
  • 1
    the other answer is better, you should accept it ;) – Barry NL May 19 '15 at 14:37
  • Well, Wildfly complains about the inner class `Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYEJB0128: EJB AsynchronousMethodLauncher of type com.acme.job.JobScheduler$AsynchronousMethodLauncher must not be inner class` – leo Sep 30 '21 at 17:22
4

I would suggest natural Java EE way:

@Singleton
public class AsyncSingletonBeanBean {

    @Resource
    private SessionContext sessionContext;

    @PostConstruct
    public void init() {
        AsyncSingletonBeanBean myBean = sessionContext.getBusinessObject(this.getClass());
        myBean.foo();
    }

    @Asynchronous
    public Future<String> foo() {
        return new AsyncResult<String>("Hello");
    }
}
Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
iskramac
  • 868
  • 6
  • 14