Top Description Inners Fields Constructors Methods
org.springframework.beans.factory.config

public Class ServiceLocatorFactoryBean

extends Object
implements FactoryBean<Object>, BeanFactoryAware, InitializingBean
Class Inheritance
All Implemented Interfaces
org.springframework.beans.factory.InitializingBean, org.springframework.beans.factory.BeanFactoryAware, org.springframework.beans.factory.Aware, org.springframework.beans.factory.FactoryBean
Imports
java.lang.reflect.Constructor, .InvocationHandler, .Method, .Proxy, java.util.Properties, org.springframework.beans.BeanUtils, .BeansException, .FatalBeanException, org.springframework.beans.factory.BeanFactory, .BeanFactoryAware, .FactoryBean, .InitializingBean, .ListableBeanFactory, org.springframework.lang.Nullable, org.springframework.util.Assert, .ReflectionUtils, .StringUtils

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 org.springframework.beans.factory.BeanFactory.

Such service locators permit the decoupling of calling code from the org.springframework.beans.factory.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 org.springframework.beans.factory.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 org.springframework.beans.factory.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 org.springframework.beans.factory.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 org.springframework.beans.factory.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.

Authors
Colin Sampaleanu, Juergen Hoeller
Since
1.1.4
See Also
setServiceLocatorInterface, setServiceMappings, ObjectFactoryCreatingFactoryBean

Nested and Inner Type Summary

Modifier and TypeClass and Description
private class
ServiceLocatorFactoryBean.ServiceLocatorInvocationHandler

Invocation handler that delegates service locator calls to the bean factory.

Field Summary

Modifier and TypeField and Description
private ListableBeanFactory
private Object
private Constructor<Exception>
private Class<?>
private Properties

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public void
afterPropertiesSet()

Implements org.springframework.beans.factory.InitializingBean.afterPropertiesSet.

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.

protected Exception

Returns:

the service locator exception to throw
createServiceLocatorException
(Constructor<Exception>
the constructor to use
exceptionConstructor
,
BeansException
the cause of the service lookup failure
cause
)

Create a service locator exception for the given cause.

protected Constructor<Exception>

Returns:

the constructor to use
determineServiceLocatorExceptionConstructor
(Class<? extends Exception>
the exception class
exceptionClass
)

Determine the constructor to use for the given service locator exception class.

public Object
getObject()

Implements org.springframework.beans.factory.FactoryBean.getObject.

Return an instance (possibly shared or independent) of the object managed by this factory.

public Class<?>
getObjectType()

Implements org.springframework.beans.factory.FactoryBean.getObjectType.

Return the type of object that this FactoryBean creates, or null if not known in advance.

public boolean
isSingleton()

Overrides default org.springframework.beans.factory.FactoryBean.isSingleton.

Is the object managed by this factory a singleton?

public void
setBeanFactory(BeanFactory
owning BeanFactory (never null). The bean can immediately call methods on the factory.
beanFactory
)

Implements org.springframework.beans.factory.BeanFactoryAware.setBeanFactory.

Callback that supplies the owning factory to a bean instance.

public void
setServiceLocatorExceptionClass(Class<? extends Exception> serviceLocatorExceptionClass)

Set the exception class that the service locator should throw if service lookup failed.

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)).

public void
setServiceMappings(Properties
mappings between service ids and bean names, with service ids as keys as bean names as values
serviceMappings
)

Set mappings between service ids (passed into the service locator) and bean names (in the bean factory).

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

beanFactoryback to summary
private ListableBeanFactory beanFactory
Annotations
@Nullable
proxyback to summary
private Object proxy
Annotations
@Nullable
serviceLocatorExceptionConstructorback to summary
private Constructor<Exception> serviceLocatorExceptionConstructor
Annotations
@Nullable
serviceLocatorInterfaceback to summary
private Class<?> serviceLocatorInterface
Annotations
@Nullable
serviceMappingsback to summary
private Properties serviceMappings
Annotations
@Nullable

Constructor Detail

ServiceLocatorFactoryBeanback to summary
public ServiceLocatorFactoryBean()

Method Detail

afterPropertiesSetback to summary
public void afterPropertiesSet()

Implements org.springframework.beans.factory.InitializingBean.afterPropertiesSet.

Doc from org.springframework.beans.factory.InitializingBean.afterPropertiesSet.

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.

Annotations
@Override
createServiceLocatorExceptionback to summary
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:Constructor<Exception>

the constructor to use

cause:BeansException

the cause of the service lookup failure

Returns:Exception

the service locator exception to throw

See Also
setServiceLocatorExceptionClass
determineServiceLocatorExceptionConstructorback to summary
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:Class<? extends Exception>

the exception class

Returns:Constructor<Exception>

the constructor to use

Annotations
@SuppressWarnings:unchecked
See Also
setServiceLocatorExceptionClass
getObjectback to summary
public Object getObject()

Implements org.springframework.beans.factory.FactoryBean.getObject.

Doc from org.springframework.beans.factory.FactoryBean.getObject.

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 pattern.

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.

As of Spring 2.0, FactoryBeans are allowed to return null objects. The factory will consider this as normal value to be used; it will not throw a FactoryBeanNotInitializedException in this case anymore. FactoryBean implementations are encouraged to throw FactoryBeanNotInitializedException themselves now, as appropriate.

Returns:Object

an instance of the bean (can be null)

Annotations
@Override
@Nullable
getObjectTypeback to summary
public Class<?> getObjectType()

Implements org.springframework.beans.factory.FactoryBean.getObjectType.

Doc from org.springframework.beans.factory.FactoryBean.getObjectType.

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 are creating 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.

Returns:Class<?>

the type of object that this FactoryBean creates, or null if not known at the time of the call

Annotations
@Override
isSingletonback to summary
public boolean isSingleton()

Overrides default org.springframework.beans.factory.FactoryBean.isSingleton.

Doc from org.springframework.beans.factory.FactoryBean.isSingleton.

Is the object managed by this factory a singleton? That is, will getObject() always return the same object (a reference that can be cached)?

Note

If a FactoryBean indicates to hold 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.

Returns:boolean

whether the exposed object is a singleton

Annotations
@Override
setBeanFactoryback to summary
public void setBeanFactory(BeanFactory beanFactory) throws BeansException

Implements org.springframework.beans.factory.BeanFactoryAware.setBeanFactory.

Doc from org.springframework.beans.factory.BeanFactoryAware.setBeanFactory.

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.

Parameters
beanFactory:BeanFactory

owning BeanFactory (never null). The bean can immediately call methods on the factory.

Annotations
@Override
Exceptions
BeansException:
in case of initialization errors
setServiceLocatorExceptionClassback to summary
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, createServiceLocatorException
setServiceLocatorInterfaceback to summary
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.

setServiceMappingsback to summary
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:Properties

mappings between service ids and bean names, with service ids as keys as bean names as values

org.springframework.beans.factory.config back to summary

private Class ServiceLocatorFactoryBean.ServiceLocatorInvocationHandler

extends Object
implements InvocationHandler
Class Inheritance
  • java.lang.Object
  • org.springframework.beans.factory.config.ServiceLocatorFactoryBean.ServiceLocatorInvocationHandler
All Implemented Interfaces
java.lang.reflect.InvocationHandler

Invocation handler that delegates service locator calls to the bean factory.

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
private Class<?>
public Object
invoke(Object
the proxy instance that the method was invoked on
proxy
,
Method
the Method instance corresponding to the interface method invoked on the proxy instance. The declaring class of the Method object will be the interface that the method was declared in, which may be a superinterface of the proxy interface that the proxy class inherits the method through.
method
,
Object[]
an array of objects containing the values of the arguments passed in the method invocation on the proxy instance, or null if interface method takes no arguments. Arguments of primitive types are wrapped in instances of the appropriate primitive wrapper class, such as java.lang.Integer or java.lang.Boolean.
args
)

Implements java.lang.reflect.InvocationHandler.invoke.

Processes a method invocation on a proxy instance and returns the result.

private Object
private String
tryGetBeanName(Object[] args)

Check whether a service id was passed in.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Constructor Detail

ServiceLocatorInvocationHandlerback to summary
private ServiceLocatorInvocationHandler()

Method Detail

getServiceLocatorMethodReturnTypeback to summary
private Class<?> getServiceLocatorMethodReturnType(Method method) throws NoSuchMethodException
invokeback to summary
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable

Implements java.lang.reflect.InvocationHandler.invoke.

Doc from java.lang.reflect.InvocationHandler.invoke.

Processes a method invocation on a proxy instance and returns the result. This method will be invoked on an invocation handler when a method is invoked on a proxy instance that it is associated with.

Parameters
proxy:Object

the proxy instance that the method was invoked on

method:Method

the Method instance corresponding to the interface method invoked on the proxy instance. The declaring class of the Method object will be the interface that the method was declared in, which may be a superinterface of the proxy interface that the proxy class inherits the method through.

args:Object[]

an array of objects containing the values of the arguments passed in the method invocation on the proxy instance, or null if interface method takes no arguments. Arguments of primitive types are wrapped in instances of the appropriate primitive wrapper class, such as java.lang.Integer or java.lang.Boolean.

Returns:Object

the value to return from the method invocation on the proxy instance. If the declared return type of the interface method is a primitive type, then the value returned by this method must be an instance of the corresponding primitive wrapper class; otherwise, it must be a type assignable to the declared return type. If the value returned by this method is null and the interface method's return type is primitive, then a NullPointerException will be thrown by the method invocation on the proxy instance. If the value returned by this method is otherwise not compatible with the interface method's declared return type as described above, a ClassCastException will be thrown by the method invocation on the proxy instance.

Annotations
@Override
Exceptions
Throwable:
the exception to throw from the method invocation on the proxy instance. The exception's type must be assignable either to any of the exception types declared in the throws clause of the interface method or to the unchecked exception types java.lang.RuntimeException or java.lang.Error. If a checked exception is thrown by this method that is not assignable to any of the exception types declared in the throws clause of the interface method, then an UndeclaredThrowableException containing the exception that was thrown by this method will be thrown by the method invocation on the proxy instance.
invokeServiceLocatorMethodback to summary
private Object invokeServiceLocatorMethod(Method method, Object[] args) throws Exception
tryGetBeanNameback to summary
private String tryGetBeanName(Object[] args)

Check whether a service id was passed in.