Package org.springframework.beans.factory.config

# Class ServiceLocatorFactoryBean

java.lang.Object
org.springframework.beans.factory.config.ServiceLocatorFactoryBean

All Implemented Interfaces:
  `Aware`, `BeanFactoryAware`, `FactoryBean<Object>`, `InitializingBean`

public class ServiceLocatorFactoryBean extends Object implements FactoryBean<Object>, BeanFactoryAware, InitializingBean
A `FactoryBean` implementation that takes an interface which must have one or more methods with the signatures `MyType xxx()` or `MyType xxx(MyIdType id)` (typically, `MyService getService()` or `MyService getService(String id)`) and creates a dynamic proxy which implements that interface, delegating to an underlying `BeanFactory`.

Such service locators permit the decoupling of calling code from the `BeanFactory` API, by using an appropriate custom locator interface. They will typically be used for prototype beans, i.e. for factory methods that are supposed to return a new instance for each call. The client receives a reference to the service locator via setter or constructor injection, to be able to invoke the locator's factory methods on demand. For singleton beans, direct setter or constructor injection of the target bean is preferable.

On invocation of the no-arg factory method, or the single-arg factory method with a String id of `null` or empty String, if exactly one bean in the factory matches the return type of the factory method, that bean is returned, otherwise a `NoSuchBeanDefinitionException` is thrown.

On invocation of the single-arg factory method with a non-null (and non-empty) argument, the proxy returns the result of a `BeanFactory.getBean(String)` call, using a stringified version of the passed-in id as bean name.

A factory method argument will usually be a String, but can also be an int or a custom enumeration type, for example, stringified via `toString`. The resulting String can be used as bean name as-is, provided that corresponding beans are defined in the bean factory. Alternatively, a custom mapping between service IDs and bean names can be defined.

By way of an example, consider the following service locator interface. Note that this interface is not dependent on any Spring APIs.

    package a.b.c;

    public interface ServiceFactory {

        public MyService getService();
    }

A sample config in an XML-based `BeanFactory` might look as follows:

    <beans>

       <!-- Prototype bean since we have state -->
       <bean id="myService" class="a.b.c.MyService" singleton="false"/>

       <!-- will lookup the above 'myService' bean by *TYPE* -->
       <bean id="myServiceFactory"
                class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean">
         <property name="serviceLocatorInterface" value="a.b.c.ServiceFactory"/>
       </bean>

       <bean id="clientBean" class="a.b.c.MyClientBean">
         <property name="myServiceFactory" ref="myServiceFactory"/>
       </bean>

    </beans>

The attendant `MyClientBean` class implementation might then look something like this:

    package a.b.c;

    public class MyClientBean {

        private ServiceFactory myServiceFactory;

        // actual implementation provided by the Spring container
        public void setServiceFactory(ServiceFactory myServiceFactory) {
            this.myServiceFactory = myServiceFactory;
        }

        public void someBusinessMethod() {
            // get a 'fresh', brand new MyService instance
            MyService service = this.myServiceFactory.getService();
            // use the service object to effect the business logic...
        }
    }

By way of an example that looks up a bean by name, consider the following service locator interface. Again, note that this interface is not dependent on any Spring APIs.

    package a.b.c;

    public interface ServiceFactory {

        public MyService getService (String serviceName);
    }

A sample config in an XML-based `BeanFactory` might look as follows:

    <beans>

       <!-- Prototype beans since we have state (both extend MyService) -->
       <bean id="specialService" class="a.b.c.SpecialService" singleton="false"/>
       <bean id="anotherService" class="a.b.c.AnotherService" singleton="false"/>

       <bean id="myServiceFactory"
                class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean">
         <property name="serviceLocatorInterface" value="a.b.c.ServiceFactory"/>
       </bean>

       <bean id="clientBean" class="a.b.c.MyClientBean">
         <property name="myServiceFactory" ref="myServiceFactory"/>
       </bean>

    </beans>

The attendant `MyClientBean` class implementation might then look something like this:

    package a.b.c;

    public class MyClientBean {

        private ServiceFactory myServiceFactory;

        // actual implementation provided by the Spring container
        public void setServiceFactory(ServiceFactory myServiceFactory) {
            this.myServiceFactory = myServiceFactory;
        }

        public void someBusinessMethod() {
            // get a 'fresh', brand new MyService instance
            MyService service = this.myServiceFactory.getService("specialService");
            // use the service object to effect the business logic...
        }

        public void anotherBusinessMethod() {
            // get a 'fresh', brand new MyService instance
            MyService service = this.myServiceFactory.getService("anotherService");
            // use the service object to effect the business logic...
        }
    }

See `ObjectFactoryCreatingFactoryBean` for an alternate approach.

Since:
  1.1.4
Author:
  Colin Sampaleanu, Juergen Hoeller
See Also:
  - `setServiceLocatorInterface(java.lang.Class<?>)`
  - `setServiceMappings(java.util.Properties)`
  - `ObjectFactoryCreatingFactoryBean`

## Field Summary

### Fields inherited from interface org.springframework.beans.factory.FactoryBean

`OBJECT_TYPE_ATTRIBUTE`

## Constructor Summary

Constructors
Constructor
Description
`ServiceLocatorFactoryBean()`

## Method Summary

Modifier and Type
Method
Description
`void`
`afterPropertiesSet()`
Invoked by the containing `BeanFactory` after it has set all bean properties and satisfied `BeanFactoryAware`, `ApplicationContextAware` etc.
`protected Exception`
`createServiceLocatorException(Constructor<Exception> exceptionConstructor, BeansException cause)`
Create a service locator exception for the given cause.
`protected Constructor<Exception>`
`determineServiceLocatorExceptionConstructor(Class<? extends Exception> exceptionClass)`
Determine the constructor to use for the given service locator exception class.
`Object`
`getObject()`
Return an instance (possibly shared or independent) of the object managed by this factory.
`Class<?>`
`getObjectType()`
Return the type of object that this FactoryBean creates, or `null` if not known in advance.
`boolean`
`isSingleton()`
Is the object managed by this factory a singleton? That is, will `FactoryBean.getObject()` always return the same object (a reference that can be cached)?
`void`
`setBeanFactory(BeanFactory beanFactory)`
Callback that supplies the owning factory to a bean instance.
`void`
`setServiceLocatorExceptionClass(Class<? extends Exception> serviceLocatorExceptionClass)`
Set the exception class that the service locator should throw if service lookup failed.
`void`
`setServiceLocatorInterface(Class<?> interfaceType)`
Set the service locator interface to use, which must have one or more methods with the signatures `MyType xxx()` or `MyType xxx(MyIdType id)` (typically, `MyService getService()` or `MyService getService(String id)`).
`void`
`setServiceMappings(Properties serviceMappings)`
Set mappings between service ids (passed into the service locator) and bean names (in the bean factory).

### Methods inherited from class java.lang.Object

`clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

## Constructor Details

### ServiceLocatorFactoryBean

public ServiceLocatorFactoryBean()

## Method Details

### setServiceLocatorInterface

public void setServiceLocatorInterface(Class<?> interfaceType)
Set the service locator interface to use, which must have one or more methods with the signatures `MyType xxx()` or `MyType xxx(MyIdType id)` (typically, `MyService getService()` or `MyService getService(String id)`). See the `class-level Javadoc` for information on the semantics of such methods.

### setServiceLocatorExceptionClass

public void setServiceLocatorExceptionClass(Class<? extends Exception> serviceLocatorExceptionClass)
Set the exception class that the service locator should throw if service lookup failed. The specified exception class must have a constructor with one of the following parameter types: `(String, Throwable)` or `(Throwable)` or `(String)`.

If not specified, subclasses of Spring's BeansException will be thrown, for example NoSuchBeanDefinitionException. As those are unchecked, the caller does not need to handle them, so it might be acceptable that Spring exceptions get thrown as long as they are just handled generically.

See Also:
  - `determineServiceLocatorExceptionConstructor(java.lang.Class<? extends java.lang.Exception>)`
  - `createServiceLocatorException(java.lang.reflect.Constructor<java.lang.Exception>, org.springframework.beans.BeansException)`

### setServiceMappings

public void setServiceMappings(Properties serviceMappings)
Set mappings between service ids (passed into the service locator) and bean names (in the bean factory). Service ids that are not defined here will be treated as bean names as-is.

The empty string as service id key defines the mapping for `null` and empty string, and for factory methods without parameter. If not defined, a single matching bean will be retrieved from the bean factory.

Parameters:
  `serviceMappings` - mappings between service ids and bean names, with service ids as keys as bean names as values

### setBeanFactory

public void setBeanFactory(BeanFactory beanFactory) throws BeansException
Description copied from interface: `BeanFactoryAware`
Callback that supplies the owning factory to a bean instance.

Invoked after the population of normal bean properties but before an initialization callback such as `InitializingBean.afterPropertiesSet()` or a custom init-method.

Specified by:
  `setBeanFactory` in interface `BeanFactoryAware`
Parameters:
  `beanFactory` - owning BeanFactory (never `null`). The bean can immediately call methods on the factory.
Throws:
  `BeansException` - in case of initialization errors
See Also:
  - `BeanInitializationException`

### afterPropertiesSet

public void afterPropertiesSet()
Description copied from interface: `InitializingBean`
Invoked by the containing `BeanFactory` after it has set all bean properties and satisfied `BeanFactoryAware`, `ApplicationContextAware` etc.

This method allows the bean instance to perform validation of its overall configuration and final initialization when all bean properties have been set.

Specified by:
  `afterPropertiesSet` in interface `InitializingBean`

### determineServiceLocatorExceptionConstructor

protected Constructor<Exception> determineServiceLocatorExceptionConstructor(Class<? extends Exception> exceptionClass)
Determine the constructor to use for the given service locator exception class. Only called in case of a custom service locator exception.

The default implementation looks for a constructor with one of the following parameter types: `(String, Throwable)` or `(Throwable)` or `(String)`.

Parameters:
  `exceptionClass` - the exception class
Returns:
  the constructor to use
See Also:
  - `setServiceLocatorExceptionClass(java.lang.Class<? extends java.lang.Exception>)`

### createServiceLocatorException

protected Exception createServiceLocatorException(Constructor<Exception> exceptionConstructor, BeansException cause)
Create a service locator exception for the given cause. Only called in case of a custom service locator exception.

The default implementation can handle all variations of message and exception arguments.

Parameters:
  `exceptionConstructor` - the constructor to use
  `cause` - the cause of the service lookup failure
Returns:
  the service locator exception to throw
See Also:
  - `setServiceLocatorExceptionClass(java.lang.Class<? extends java.lang.Exception>)`

### getObject

@Nullable public Object getObject()
Description copied from interface: `FactoryBean`
Return an instance (possibly shared or independent) of the object managed by this factory.

As with a `BeanFactory`, this allows support for both the Singleton and Prototype design patterns.

If this FactoryBean is not fully initialized yet at the time of the call (for example because it is involved in a circular reference), throw a corresponding `FactoryBeanNotInitializedException`.

FactoryBeans are allowed to return `null` objects. The bean factory will consider this as a normal value to be used and will not throw a `FactoryBeanNotInitializedException` in this case. However, FactoryBean implementations are encouraged to throw `FactoryBeanNotInitializedException` themselves, as appropriate.

Specified by:
  `getObject` in interface `FactoryBean<Object>`
Returns:
  an instance of the bean (can be `null`)
See Also:
  - `FactoryBeanNotInitializedException`

### getObjectType

@Nullable public Class<?> getObjectType()
Description copied from interface: `FactoryBean`
Return the type of object that this FactoryBean creates, or `null` if not known in advance.

This allows one to check for specific types of beans without instantiating objects, for example on autowiring.

In the case of implementations that create a singleton object, this method should try to avoid singleton creation as far as possible; it should rather estimate the type in advance. For prototypes, returning a meaningful type here is advisable too.

This method can be called before this FactoryBean has been fully initialized. It must not rely on state created during initialization; of course, it can still use such state if available.

NOTE: Autowiring will simply ignore FactoryBeans that return `null` here. Therefore, it is highly recommended to implement this method properly, using the current state of the FactoryBean.

Specified by:
  `getObjectType` in interface `FactoryBean<Object>`
Returns:
  the type of object that this FactoryBean creates, or `null` if not known at the time of the call
See Also:
  - `ListableBeanFactory.getBeansOfType(java.lang.Class<T>)`

### isSingleton

public boolean isSingleton()
Description copied from interface: `FactoryBean`
Is the object managed by this factory a singleton? That is, will `FactoryBean.getObject()` always return the same object (a reference that can be cached)?

NOTE: If a FactoryBean indicates that it holds a singleton object, the object returned from `getObject()` might get cached by the owning BeanFactory. Hence, do not return `true` unless the FactoryBean always exposes the same reference.

The singleton status of the FactoryBean itself will generally be provided by the owning BeanFactory; usually, it has to be defined as singleton there.

NOTE: This method returning `false` does not necessarily indicate that returned objects are independent instances. An implementation of the extended `SmartFactoryBean` interface may explicitly indicate independent instances through its `SmartFactoryBean.isPrototype()` method. Plain `FactoryBean` implementations which do not implement this extended interface are simply assumed to always return independent instances if the `isSingleton()` implementation returns `false`.

The default implementation returns `true`, since a `FactoryBean` typically manages a singleton instance.

Specified by:
  `isSingleton` in interface `FactoryBean<Object>`
Returns:
  whether the exposed object is a singleton
See Also:
  - `FactoryBean.getObject()`
  - `SmartFactoryBean.isPrototype()`