package eu.dnetlib.enabling.tools;

import org.springframework.beans.factory.annotation.Required;

/**
 * This service locator returns always one service instance.
 * 
 * Usually declared as a spring bean an injected in service when a static configuration is needed.
 * 
 * @author marko
 * 
 * @param <T>
 *            the type of the service
 */
public class StaticServiceLocator<T> implements ServiceLocator<T> {

	/**
	 * static service reference.
	 */
	private T service;

	/**
	 * default constructor. initialize with setter.
	 */
	public StaticServiceLocator() {
		// no operation
	}

	/**
	 * construct a static service locator pointing at a given service.
	 * 
	 * @param service
	 *            service
	 */
	public StaticServiceLocator(final T service) {
		this.service = service;
	}

	/** 
	 * The usual usage pattern of service locators is to call chain a direct call
	 * on the result of this method. In order to avoid nullpointer exception, this method throws an exception
	 * with a better explanation, in case the service is null. 
	 * 
	 * TODO: consider using checked exceptions.
	 * 
	 * {@inheritDoc}
	 * @see eu.dnetlib.enabling.tools.ServiceLocator#getService()
	 */
	@Override
	public T getService() {
		if (service == null)
			throw new IllegalStateException("cannot find service, check configuration");
		return service;
	}
	
	@Required
	public void setService(final T service) {
		this.service = service;
	}

}
