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 as the producer. When a disposer method declares additional parameters, these are treated as injection points by Weld, allowing us to inject loggers or other beans that are needed to perform the cleanup process.