Waiting for Life Cycle Events

Liferay registers life cycle events like portal and portlet initialization into the OSGi service registry. Your OSGi classes can listen for these service registrations to wait for the respective life cycle events before executing certain tasks. The ModuleServiceLifecycle interface defines the names for these events:

  • LICENSE_INSTALL
  • PORTAL_INITIALIZED
  • PORTLETS_INITIALIZED

The following sample listens for the PORTAL_INITIALIZED event and logs a message in the console.

Deploy the Sample Code

Start a new Liferay instance by running

docker run -it -m 8g -p 8080:8080 liferay/portal:7.4.3.132-ga132

Sign in to Liferay at http://localhost:8080. Use the email address test@liferay.com and the password test. When prompted, change the password to learn.

Then, follow these steps:

  1. Download and unzip the example.

    curl https://resources.learn.liferay.com/examples/liferay-h4l9.zip -O
    
    unzip liferay-h4l9.zip
    
  2. From the module root, build and deploy.

    ./gradlew deploy -Ddeploy.docker.container.id=$(docker ps -lq)
    
    Note

    This command is the same as copying the deployed jars to /opt/liferay/osgi/modules on the Docker container.

  3. Confirm the deployment in the Liferay Docker container console.

    STARTED com.acme.h4l9.impl.0.0 [1009]
    
  4. In another tab, stop the Liferay container.

    docker stop $(docker ps -lq)
    
  5. Restart the Liferay container. When Liferay finishes starting up, it registers the PORTAL_INITIALIZED event.

    docker start $(docker ps -lq)
    
  6. The sample module listens to the life cycle event and prints this message to the Liferay Docker container console:

    INFO  [http-nio-8080-exec-6][H4L9PortalInstanceLifecycleListener:20] Invoking #activate
    

Taking Action from a Component

Declarative Services make it easy to target the event you want.

Target the name of the required life cycle events using the @Reference annotation. The component only begins executing its tasks once the chosen event is registered.

@Reference(target = ModuleServiceLifecycle.PORTAL_INITIALIZED)
private ModuleServiceLifecycle _moduleServiceLifecycle;
@Activate
protected void activate() {
	if (_log.isInfoEnabled()) {
		_log.info("Invoking #activate");
	}
}