How to register a PrivilegeListener

What is a PrivilegeListener?

A PrivilegeListener is a java class that implements the org.openmrs.PrivilegeListener interface, registered instances of  PrivilegeListeners  get notified of all the privilege checks that are made as the application executes by invoking the privilegeChecked() method. The actual paramater values passed to the method are; the user for whom the check was made, the checked privilege and a boolean value that specifies if the user has the privilege or not.  The listeners are registered as spring managed beans using the @Component annotation or from the application context file.

Registering a PrivilegeListener

1. Using the @Component annotation

@Component
public static class MyListener implements PrivilegeListener {

    @Override
    public void privilegeChecked(User user, String privilege, boolean hasPrivilege) {
       //...do something
    }
}

2. From the application context file

This approach involves 2 steps as shown below:

Coding the listener class:

public static class MyListener implements PrivilegeListener {

    @Override
    public void privilegeChecked(User user, String privilege, boolean hasPrivilege) {
       //...do something
    }
}

Registering the listener in the application context file (this could be from a module):

<bean id="myListener" class="org.openmrs.mypackage.MyListener" />

Now our listeners are ready to receive notifications as privileges checks are made.

Example Usage:

The Privilege Helper Module is a good example usage of PrivilegeListeners.