001/* 002 * Copyright 2002-2007 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.beans.factory.serviceloader; 018 019import java.util.Iterator; 020import java.util.ServiceLoader; 021 022import org.springframework.beans.factory.BeanClassLoaderAware; 023import org.springframework.lang.Nullable; 024 025/** 026 * {@link org.springframework.beans.factory.FactoryBean} that exposes the 027 * 'primary' service for the configured service class, obtained through 028 * the JDK 1.6 {@link java.util.ServiceLoader} facility. 029 * 030 * @author Juergen Hoeller 031 * @since 2.5 032 * @see java.util.ServiceLoader 033 */ 034public class ServiceFactoryBean extends AbstractServiceLoaderBasedFactoryBean implements BeanClassLoaderAware { 035 036 @Override 037 protected Object getObjectToExpose(ServiceLoader<?> serviceLoader) { 038 Iterator<?> it = serviceLoader.iterator(); 039 if (!it.hasNext()) { 040 throw new IllegalStateException( 041 "ServiceLoader could not find service for type [" + getServiceType() + "]"); 042 } 043 return it.next(); 044 } 045 046 @Override 047 @Nullable 048 public Class<?> getObjectType() { 049 return getServiceType(); 050 } 051 052}