Liferay Service Hook to override Liferay Existing Service

Today we override User Service method  - getUserCount() 

Here we create a class that extend the particular wrapper class and just provide the entries of our custom class in liferay-hook.xml so that liferay use our services instead of Original.

Step 1:-Create a liferay Plug in project and Select Plugin type Hook








Step 2:-Create a Hook in the Project

Right Click on Project -->New-->Liferay Hook Configuration--->Select Services


Click Next--->Click Add-->Select Service Type(UserLocalService)


For Impl Class

Click New-->Give Package Name and your Impl Class Name

Then Click Finish

This step automatically Create the entry in  liferay-hook.xml. 

<hook>
<service>
<service-type>com.liferay.portal.service.UserLocalService</service-type>
<service-impl>com.ipg.MyUserLocalService</service-impl>
</service>
</hook>






Step 3:-Override the getUserCount()

Open MyUserLocalService and override getUserCount()


package com.ipg;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.service.UserLocalServiceWrapper;
import com.liferay.portal.service.UserLocalService;

public class MyUserLocalService extends UserLocalServiceWrapper {
public MyUserLocalService(UserLocalService userLocalService) {
super(userLocalService);
}

@Override
public int getUsersCount() throws SystemException {
System.out.println("This text is from getUsersCount ");
return super.getUsersCount();
}
}

Step 4:-Deploy the Hook

Deploy the hook and call getUsersCount() from your portlet :-


public void doView(RenderRequest renderRequest,
RenderResponse renderResponse) throws IOException, PortletException {
try {
UserLocalServiceUtil.getUsersCount();

} catch (SystemException e) {
e.printStackTrace();
}
super.doView(renderRequest, renderResponse);
}

Output:-This text is from getUsersCount 

Thats it every time you call getUserCount() it will call your method rather than original one.