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; 023 024/** 025 * {@link org.springframework.beans.factory.FactoryBean} that exposes the 026 * 'primary' service for the configured service class, obtained through 027 * the JDK 1.6 {@link java.util.ServiceLoader} facility. 028 * 029 * @author Juergen Hoeller 030 * @since 2.5 031 * @see java.util.ServiceLoader 032 */ 033public class ServiceFactoryBean extends AbstractServiceLoaderBasedFactoryBean implements BeanClassLoaderAware { 034 035 @Override 036 protected Object getObjectToExpose(ServiceLoader<?> serviceLoader) { 037 Iterator<?> it = serviceLoader.iterator(); 038 if (!it.hasNext()) { 039 throw new IllegalStateException( 040 "ServiceLoader could not find service for type [" + getServiceType() + "]"); 041 } 042 return it.next(); 043 } 044 045 @Override 046 public Class<?> getObjectType() { 047 return getServiceType(); 048 } 049 050}