Skip to main content
Developer System administrator Jahia 8.2

Can I run code when my module is activated on a site?

Question

Can I run code when my module is activated on a site?

Answer

Yes. Jahia publishes a Spring application event when a module is installed on a site: JahiaTemplateManagerService.ModuleDeployedOnSiteEvent.

Declare a Spring bean in your module that listens for it:

import org.jahia.services.templates.JahiaTemplateManagerService.ModuleDeployedOnSiteEvent;
import org.springframework.context.ApplicationListener;

public class MySiteActivationListener implements ApplicationListener<ModuleDeployedOnSiteEvent> {

    @Override
    public void onApplicationEvent(ModuleDeployedOnSiteEvent event) {
        String sitePath = event.getTargetSitePath();   // e.g. /sites/mySite
        ...
    }
}

This is the mechanism core itself uses - WorkflowService, BundleScriptResolver and the GWT CacheHelper all listen for this event to react to a site's module set changing.

Two things that will catch you out

The event fires on uninstall too. Despite the name, it is published from the uninstall paths as well as the install one - installModules(...), uninstallModules(...) and uninstallModulesFromAllSites(...) all publish it.

The event carries only the site path. There is no module name and no install/uninstall flag on it:

public String getTargetSitePath()   // that is the entire payload

So a listener cannot tell from the event alone whether your module was just added or just removed, or even whether the change involved your module at all. It is a "the module set on this site changed" signal, not "my module was activated".

Act on it by reading the current state rather than trusting the event:

public void onApplicationEvent(ModuleDeployedOnSiteEvent event) {
    String sitePath = event.getTargetSitePath();
    // look up the site and check whether this module is now in its installed modules
    // before doing any work
}

Writing a listener that assumes "activated" will run your activation logic on deactivation too.

It is published twice

Core publishes the same event through both the Spring applicationEventPublisher and Jahia's own jahiaEventService. If you subscribe through both, you will handle it twice - pick one.

Not the same as module start

ModuleDeployedOnSiteEvent is about a site. Code that should run once when the module itself starts on the platform belongs in the module's own lifecycle - an OSGi bundle activator or a Spring bean's init method - and will run whether or not any site uses the module.


This article was drafted with AI assistance, then reviewed and curated by Jahia Customer Support engineers before publication.