All beans managed by the Errai IOC container support the @PostConstruct and @PreDestroy annotations.
Beans which have methods annotated with @PostConstruct are guaranteed to have those methods called before the bean is put into service, and only after all dependencies within its graph has been satisfied.
Beans are also guaranteed to have their @PreDestroy annotated methods called before they are destroyed by the bean manager.
|This cannot be guaranteed when the browser DOM is destroyed prematurely due to: closing the browser window; closing a tab; refreshing the page, etc.|
Beans under management of Errai IOC, of any scope, can be explicitly destroyed through the client bean manager. Destruction of a managed bean is accomplished by passing a reference to the destroyBean() method of the bean manager.
When the bean manager "destroys" the bean, any pre-destroy methods the bean declares are called, it is taken out of service and no longer tracked by the bean manager. If there are references on the bean by other objects, the bean will continue to be accessible to those objects.
|Container managed resources that are dependent on the bean such as bus service endpoints or CDI event observers will also be automatically destroyed when the bean is destroyed.|
Another important consideration is the rule, "all beans created together are destroyed together." Consider the following example:
In this example we pass the instance of AnotherBean, created as a dependency of SimpleBean, to the bean manager for destruction. Because this bean was created at the same time as its parent, its destruction will also result in the destruction of SimpleBean; thus, this action will result in the @PreDestroy cleanUp() method of SimpleBean being invoked.
Another way which beans can be destroyed is through the use of the injectable org.jboss.errai.ioc.client.api.Disposer<T> class. The class provides a straight forward way of disposing of bean type.