Skip to content

Lifecycle Management

Randgalt edited this page Feb 20, 2013 · 26 revisions

There is much more to an object’s lifecyle than just allocation via new. In particular, there is an important anti-pattern regarding letting this “escape” from a constructor. This page describes the problem in detail.

In Governator, an object can go through a number of steps in its lifecycle. Annotations are available to define methods for these steps. The steps are:

Allocation (via Guice)
     |
     v
Pre Configuration
     |
     v
Configuration
     |
     V
Set Resources
     |
     V
Post Construction
     |
     V
Validation and Warm Up
     |
     V
  -- application runs until termination, then... --    
     |
     V
Pre Destroy

Here are the annotations available:

Annotation Target Description
@PreConfiguration Methods Called prior to Configuration Mapping
@Resource/@Resources Classes,Methods,Fields Called after Configuration Mapping. See JDK Docs for details. Also, see the section on ResourceLocators below.
@PostConstruct Methods Called after Resource setting
@Min, @Max, etc. Fields Processed when LifecycleManager.start() is called. See Field Validation for details.
@WarmUp Methods Called when LifecycleManager.start() is called. Executed in parallel in the background. See Warm Up for details.
@PreDestroy Methods Called when LifecycleManager.close() is called.

Resources and ResourceLocators

The @Resource and @Resources annotations are processed by a Governator defined interface: ResourceLocator.

public interface ResourceLocator {
    public Object locate(Resource resource, ResourceLocator nextInChain) throws Exception;
}

You can bind one or more ResourceLocators in your BootstrapModule using the bindResourceLocator() method. There is a default ResourceLocator that calls injector.getInstance(resource.type()). When the locate() method of your ResourceLocator is called, the Resource object’s name and type will have been updated if defaults were used. Your ResourceLocator can load the resource anyway it chooses. i.e. via JNDI, etc.