Model Listener in Liferay 6
October 19, 2010 7:25 PM
Since wiki-page
on Liferay.com has out of dated information (not actual for
Liferay 6) want to write small reminder how to define model listener
in Liferay 6.
What is Model Listener
Model Listener - is a special call-back class, what called then some
operation happens with some model - core portal model or any model
defined in the portlets.
ModelListener interface looks like
public interface ModelListener<T> {
public void onAfterAddAssociation(Object classPK, String associationClassName, Object associationClassPK) throws ModelListenerException;
public void onAfterCreate(T model) throws ModelListenerException;
public void onAfterRemove(T model) throws ModelListenerException;
public void onAfterRemoveAssociation(Object classPK, String associationClassName, Object associationClassPK) throws ModelListenerException;
public void onAfterUpdate(T model) throws ModelListenerException;
public void onBeforeAddAssociation(Object classPK, String associationClassName, Object associationClassPK) throws ModelListenerException;
public void onBeforeCreate(T model) throws ModelListenerException;
public void onBeforeRemove(T model) throws ModelListenerException;
public void onBeforeRemoveAssociation(Object classPK, String associationClassName, Object associationClassPK) throws ModelListenerException;
public void onBeforeUpdate(T model) throws ModelListenerException;
}
It is very close to Hibernate Listener (I think it is based on it)
and allow to write reaction on any action with the object. I hope
names of methods are clear.
How to implement Model Listener
To implement own listener on some Model (for example User) yin your
portlet you need:
1. define property hook in your portlet. In file
WEB-INF/liferay-hook.xml you need to have something like:
<hook>
<portal-properties>portal.properties</portal-properties>
</hook>
2. In file WEB-INF/src/portal.properties define hook
for specific model:
value.object.listener.com.liferay.portal.model.User=my.hook.UserListener
3. Implement class by inheriting it from BaseModelListener<T>
(in our case BaseModelListener<User>) and implementing only
method we want to call-back:
public class GroupListener extends BaseModelListener<Group> {
@Override
public void onAfterCreate(Group group) throws ModelListenerException {
// do something here
}
}