Message Boards

LocalServiceUtil classes

David Fenández, modified 5 Years ago.

LocalServiceUtil classes

New Member Posts: 15 Join Date: 5/18/17 Recent Posts
In Liferay 7, why do not you want to use the LocalServiceUtil classes? Instead of these classes the LocalService classes must be injected into the OSGI module.
thumbnail
David H Nebinger, modified 5 Years ago.

RE: LocalServiceUtil classes

Liferay Legend Posts: 14919 Join Date: 9/2/06 Recent Posts
When you use an @Reference injection, your module will wait until the identified service is available for injection.

When you use the LocalServiceUtil classes, you are relying on an external ServiceTracker to have access to a service, but it often does not care if there is an available service or not.

In many cases you might only be using the service as a result of user activity with your portlet, for example, so you might not see an immediate impact.

But if, for example, you are trying to do something at startup, such as add a new Role during module startup, the service may not yet be available. When using @Reference, you don't have a problem, but when using the LocalServiceUtil you can actually get a null pointer exception.

So rather than trying to guess, can I use the LocalServiceUtil not or should I use the @Reference depending upon context, I always recommend that you stick with the @Reference option since it guarantees the service will be available when you need it.