-*LocalServiceUtil.getService returns null.

Vishnu S Kumar, modified 6 Years ago. Regular Member Posts: 131 Join Date: 7/28/17 Recent Posts
Following is the auto-generated code by the service builder inside the UserLocalServiceUtil class.

    public static UserLocalService getService() {
        return _serviceTracker.getService();
    } 
    
&nbsp;&nbsp; &nbsp;private static ServiceTracker<userlocalservice, userlocalservice> _serviceTracker =
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;ServiceTrackerFactory.open(UserLocalService.class);</userlocalservice,>


When I invoke UserLocalServiceUtil.getService(),  it returns null.
thumbnail
David H Nebinger, modified 6 Years ago. Liferay Legend Posts: 14933 Join Date: 9/2/06 Recent Posts
It is why you should not be using any static service util classes, local or remote.

Getting a null back can happen for any number of reasons; service is not available (so service tracker doesn't have an instance to return), service has not started yet (waiting on other dependency resolutions), etc.

You should only be @Reference injecting the services you need. That way your component will not start until the service is ready and injected and you won't have to deal with NPEs.

And sure, your component might not start if the service never becomes available, but that is not the fault of your component, it is the fault of your service. You don't want your component to start unless the service is ready.
Vishnu S Kumar, modified 6 Years ago. Regular Member Posts: 131 Join Date: 7/28/17 Recent Posts
Thanks David. I'll use the @Reference to inject the service.

David H Nebinger:

It is why you should not be using any static service util classes, local or remote.

Getting a null back can happen for any number of reasons; service is not available (so service tracker doesn't have an instance to return), service has not started yet (waiting on other dependency resolutions), etc.

You should only be @Reference injecting the services you need. That way your component will not start until the service is ready and injected and you won't have to deal with NPEs.

And sure, your component might not start if the service never becomes available, but that is not the fault of your component, it is the fault of your service. You don't want your component to start unless the service is ready.