Cleanup of produced beans

Often, the producers we create produce a bean that either requires explicit destruction or closure, or another object may need to be destroyed once the bean that was using it is no longer required.

For these situations, CDI provides a means by which we can perform a customized cleanup within our application by creating a disposer method to match the producer.

public class AccountDatabase {

  @Produces
  @ConversationScoped
  @AccountDB
  public EntityManager create(EntityManagerFactory factory) {
    return factory.createEntityManager();
  }

  public void close(@Disposes @AccountDB EntityManager em) {
    em.close();
  }
}

A disposer method is required to have a single parameter annotated with @Disposes that has the same bean type and qualifiers ...

Get JBoss Weld CDI for Java Platform now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.