spring-framework / org.springframework.beans.factory.config

Package org.springframework.beans.factory.config

Types

BeanDefinitionVisitor

open class BeanDefinitionVisitor

Visitor class for traversing BeanDefinition objects, in particular the property values and constructor argument values contained in them, resolving bean metadata values.

Used by PropertyPlaceholderConfigurer to parse all String values contained in a BeanDefinition, resolving any placeholders found.

BeanExpressionResolver

interface BeanExpressionResolver

Strategy interface for resolving a value through evaluating it as an expression, if applicable.

A raw org.springframework.beans.factory.BeanFactory does not contain a default implementation of this strategy. However, org.springframework.context.ApplicationContext implementations will provide expression support out of the box.

CustomEditorConfigurer

open class CustomEditorConfigurer : BeanFactoryPostProcessor, Ordered

BeanFactoryPostProcessor implementation that allows for convenient registration of custom PropertyEditor.

In case you want to register PropertyEditor instances, the recommended usage as of Spring 2.0 is to use custom PropertyEditorRegistrar implementations that in turn register any desired editor instances on a given org.springframework.beans.PropertyEditorRegistry. Each PropertyEditorRegistrar can register any number of custom editors.

 <bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="propertyEditorRegistrars"> <list> <bean class="mypackage.MyCustomDateEditorRegistrar"/> <bean class="mypackage.MyObjectEditorRegistrar"/> </list> </property> </bean> 

It's perfectly fine to register PropertyEditor classes via the customEditors property. Spring will create fresh instances of them for each editing attempt then:

 <bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"> <map> <entry key="java.util.Date" value="mypackage.MyCustomDateEditor"/> <entry key="mypackage.MyObject" value="mypackage.MyObjectEditor"/> </map> </property> </bean> 

Note, that you shouldn't register PropertyEditor bean instances via the customEditors property as PropertyEditors are stateful and the instances will then have to be synchronized for every editing attempt. In case you need control over the instantiation process of PropertyEditors, use a PropertyEditorRegistrar to register them.

Also supports "java.lang.String[]"-style array class names and primitive class names (e.g. "boolean"). Delegates to ClassUtils for actual class name resolution.

NOTE: Custom property editors registered with this configurer do not apply to data binding. Custom editors for data binding need to be registered on the org.springframework.validation.DataBinder: Use a common base class or delegate to common PropertyEditorRegistrar implementations to reuse editor registration there.

CustomScopeConfigurer

open class CustomScopeConfigurer : BeanFactoryPostProcessor, BeanClassLoaderAware, Ordered

Simple BeanFactoryPostProcessor implementation that registers custom Scope with the containing ConfigurableBeanFactory.

Will register all of the supplied scopes with the ConfigurableListableBeanFactory that is passed to the #postProcessBeanFactory(ConfigurableListableBeanFactory) method.

This class allows for declarative registration of custom scopes. Alternatively, consider implementing a custom BeanFactoryPostProcessor that calls ConfigurableBeanFactory#registerScope programmatically.

DeprecatedBeanWarner

open class DeprecatedBeanWarner : BeanFactoryPostProcessor

Bean factory post processor that logs a warning for Deprecated beans.

DestructionAwareBeanPostProcessor

interface DestructionAwareBeanPostProcessor : BeanPostProcessor

Subinterface of BeanPostProcessor that adds a before-destruction callback.

The typical usage will be to invoke custom destruction callbacks on specific bean types, matching corresponding initialization callbacks.

EmbeddedValueResolver

open class EmbeddedValueResolver : StringValueResolver

StringValueResolver adapter for resolving placeholders and expressions against a ConfigurableBeanFactory.

Note that this adapter resolves expressions as well, in contrast to the ConfigurableBeanFactory#resolveEmbeddedValue method. The BeanExpressionContext used is for the plain bean factory, with no scope specified for any contextual objects to access.

FieldRetrievingFactoryBean

open class FieldRetrievingFactoryBean : FactoryBean<Any>, BeanNameAware, BeanClassLoaderAware, InitializingBean

FactoryBean which retrieves a static or non-static field value.

Typically used for retrieving public static final constants. Usage example:

// standard definition for exposing a static field, specifying the "staticField" property <bean id="myField" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"> <property name="staticField" value="java.sql.Connection.TRANSACTION_SERIALIZABLE"/> </bean> // convenience version that specifies a static field pattern as bean name <bean id="java.sql.Connection.TRANSACTION_SERIALIZABLE" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"/>

If you are using Spring 2.0, you can also use the following style of configuration for public static fields.

<util:constant static-field="java.sql.Connection.TRANSACTION_SERIALIZABLE"/>

InstantiationAwareBeanPostProcessorAdapter

abstract class InstantiationAwareBeanPostProcessorAdapter : SmartInstantiationAwareBeanPostProcessor

Adapter that implements all methods on SmartInstantiationAwareBeanPostProcessor as no-ops, which will not change normal processing of each bean instantiated by the container. Subclasses may override merely those methods that they are actually interested in.

Note that this base class is only recommendable if you actually require InstantiationAwareBeanPostProcessor functionality. If all you need is plain BeanPostProcessor functionality, prefer a straight implementation of that (simpler) interface.

ListFactoryBean

open class ListFactoryBean : AbstractFactoryBean<MutableList<Any>>

Simple factory for shared List instances. Allows for central setup of Lists via the "list" element in XML bean definitions.

MapFactoryBean

open class MapFactoryBean : AbstractFactoryBean<MutableMap<Any, Any>>

Simple factory for shared Map instances. Allows for central setup of Maps via the "map" element in XML bean definitions.

MethodInvokingBean

open class MethodInvokingBean : ArgumentConvertingMethodInvoker, BeanClassLoaderAware, BeanFactoryAware, InitializingBean

Simple method invoker bean: just invoking a target method, not expecting a result to expose to the container (in contrast to MethodInvokingFactoryBean).

This invoker supports any kind of target method. A static method may be specified by setting the targetMethod property to a String representing the static method name, with targetClass specifying the Class that the static method is defined on. Alternatively, a target instance method may be specified, by setting the targetObject property as the target object, and the targetMethod property as the name of the method to call on that target object. Arguments for the method invocation may be specified by setting the arguments property.

This class depends on #afterPropertiesSet() being called once all properties have been set, as per the InitializingBean contract.

An example (in an XML based bean factory definition) of a bean definition which uses this class to call a static initialization method:

 <bean id="myObject" class="org.springframework.beans.factory.config.MethodInvokingBean"> <property name="staticMethod" value="com.whatever.MyClass.init"/> </bean>

An example of calling an instance method to start some server bean:

 <bean id="myStarter" class="org.springframework.beans.factory.config.MethodInvokingBean"> <property name="targetObject" ref="myServer"/> <property name="targetMethod" value="start"/> </bean>

MethodInvokingFactoryBean

open class MethodInvokingFactoryBean : MethodInvokingBean, FactoryBean<Any>

FactoryBean which returns a value which is the result of a static or instance method invocation. For most use cases it is better to just use the container's built-in factory method support for the same purpose, since that is smarter at converting arguments. This factory bean is still useful though when you need to call a method which doesn't return any value (for example, a static class method to force some sort of initialization to happen). This use case is not supported by factory methods, since a return value is needed to obtain the bean instance.

Note that as it is expected to be used mostly for accessing factory methods, this factory by default operates in a singleton fashion. The first request to #getObject by the owning bean factory will cause a method invocation, whose return value will be cached for subsequent requests. An internal singleton property may be set to "false", to cause this factory to invoke the target method each time it is asked for an object.

NOTE: If your target method does not produce a result to expose, consider MethodInvokingBean instead, which avoids the type determination and lifecycle limitations that this MethodInvokingFactoryBean comes with.

This invoker supports any kind of target method. A static method may be specified by setting the targetMethod property to a String representing the static method name, with targetClass specifying the Class that the static method is defined on. Alternatively, a target instance method may be specified, by setting the targetObject property as the target object, and the targetMethod property as the name of the method to call on that target object. Arguments for the method invocation may be specified by setting the arguments property.

This class depends on #afterPropertiesSet() being called once all properties have been set, as per the InitializingBean contract.

An example (in an XML based bean factory definition) of a bean definition which uses this class to call a static factory method:

 <bean id="myObject" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="com.whatever.MyClassFactory.getInstance"/> </bean>

An example of calling a static method then an instance method to get at a Java system property. Somewhat verbose, but it works.

 <bean id="sysProps" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetClass" value="java.lang.System"/> <property name="targetMethod" value="getProperties"/> </bean> <bean id="javaVersion" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetObject" ref="sysProps"/> <property name="targetMethod" value="getProperty"/> <property name="arguments" value="java.version"/> </bean>

ObjectFactoryCreatingFactoryBean

open class ObjectFactoryCreatingFactoryBean : AbstractFactoryBean<ObjectFactory<Any>>

A org.springframework.beans.factory.FactoryBean implementation that returns a value which is an org.springframework.beans.factory.ObjectFactory that in turn returns a bean sourced from a org.springframework.beans.factory.BeanFactory.

As such, this may be used to avoid having a client object directly calling org.springframework.beans.factory.BeanFactory#getBean(String) to get a (typically prototype) bean from a org.springframework.beans.factory.BeanFactory, which would be a violation of the inversion of control principle. Instead, with the use of this class, the client object can be fed an org.springframework.beans.factory.ObjectFactory instance as a property which directly returns only the one target bean (again, which is typically a prototype bean).

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" scope="prototype"/> <bean id="myServiceFactory" class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean"> <property name="targetBeanName"><idref local="myService"/></property> </bean> <bean id="clientBean" class="a.b.c.MyClientBean"> <property name="myServiceFactory" ref="myServiceFactory"/> </bean> </beans>

The attendant MyClientBean class implementation might look something like this:

package a.b.c; import org.springframework.beans.factory.ObjectFactory; public class MyClientBean { private ObjectFactory<MyService> myServiceFactory; public void setMyServiceFactory(ObjectFactory<MyService> myServiceFactory) { this.myServiceFactory = myServiceFactory; } public void someBusinessMethod() { // get a 'fresh', brand new MyService instance MyService service = this.myServiceFactory.getObject(); // use the service object to effect the business logic... } }

An alternate approach to this application of an object creational pattern would be to use the ServiceLocatorFactoryBean to source (prototype) beans. The ServiceLocatorFactoryBean approach has the advantage of the fact that one doesn't have to depend on any Spring-specific interface such as org.springframework.beans.factory.ObjectFactory, but has the disadvantage of requiring runtime class generation. Please do consult the ServiceLocatorFactoryBean for a fuller discussion of this issue.

PreferencesPlaceholderConfigurer

open class PreferencesPlaceholderConfigurer : PropertyPlaceholderConfigurer, InitializingBean

Subclass of PropertyPlaceholderConfigurer that supports JDK 1.4's Preferences API (java.util.prefs).

Tries to resolve placeholders as keys first in the user preferences, then in the system preferences, then in this configurer's properties. Thus, behaves like PropertyPlaceholderConfigurer if no corresponding preferences defined.

Supports custom paths for the system and user preferences trees. Also supports custom paths specified in placeholders ("myPath/myPlaceholderKey"). Uses the respective root node if not specified.

PropertiesFactoryBean

open class PropertiesFactoryBean : PropertiesLoaderSupport, FactoryBean<Properties>, InitializingBean

Allows for making a properties file from a classpath location available as Properties instance in a bean factory. Can be used to populate any bean property of type Properties via a bean reference.

Supports loading from a properties file and/or setting local properties on this FactoryBean. The created Properties instance will be merged from loaded and local values. If neither a location nor local properties are set, an exception will be thrown on initialization.

Can create a singleton or a new object on each request. Default is a singleton.

PropertyOverrideConfigurer

open class PropertyOverrideConfigurer : PropertyResourceConfigurer

Property resource configurer that overrides bean property values in an application context definition. It pushes values from a properties file into bean definitions.

Configuration lines are expected to be of the following form:

beanName.property=value
Example properties file:
dataSource.driverClassName=com.mysql.jdbc.Driver dataSource.url=jdbc:mysql:mydb
In contrast to PropertyPlaceholderConfigurer, the original definition can have default values or no values at all for such bean properties. If an overriding properties file does not have an entry for a certain bean property, the default context definition is used.

Note that the context definition is not aware of being overridden; so this is not immediately obvious when looking at the XML definition file. Furthermore, note that specified override values are always literal values; they are not translated into bean references. This also applies when the original value in the XML bean definition specifies a bean reference.

In case of multiple PropertyOverrideConfigurers that define different values for the same bean property, the last one will win (due to the overriding mechanism).

Property values can be converted after reading them in, through overriding the convertPropertyValue method. For example, encrypted values can be detected and decrypted accordingly before processing them.

PropertyPathFactoryBean

open class PropertyPathFactoryBean : FactoryBean<Any>, BeanNameAware, BeanFactoryAware

FactoryBean that evaluates a property path on a given target object.

The target object can be specified directly or via a bean name.

Usage examples:

<!-- target bean to be referenced by name --> <bean id="tb" class="org.springframework.beans.TestBean" singleton="false"> <property name="age" value="10"/> <property name="spouse"> <bean class="org.springframework.beans.TestBean"> <property name="age" value="11"/> </bean> </property> </bean> <!-- will result in 12, which is the value of property 'age' of the inner bean --> <bean id="propertyPath1" class="org.springframework.beans.factory.config.PropertyPathFactoryBean"> <property name="targetObject"> <bean class="org.springframework.beans.TestBean"> <property name="age" value="12"/> </bean> </property> <property name="propertyPath" value="age"/> </bean> <!-- will result in 11, which is the value of property 'spouse.age' of bean 'tb' --> <bean id="propertyPath2" class="org.springframework.beans.factory.config.PropertyPathFactoryBean"> <property name="targetBeanName" value="tb"/> <property name="propertyPath" value="spouse.age"/> </bean> <!-- will result in 10, which is the value of property 'age' of bean 'tb' --> <bean id="tb.age" class="org.springframework.beans.factory.config.PropertyPathFactoryBean"/>

If you are using Spring 2.0 and XML Schema support in your configuration file(s), you can also use the following style of configuration for property path access. (See also the appendix entitled 'XML Schema-based configuration' in the Spring reference manual for more examples.)

 <!-- will result in 10, which is the value of property 'age' of bean 'tb' --> <util:property-path id="name" path="testBean.age"/>
Thanks to Matthias Ernst for the suggestion and initial prototype!

PropertyPlaceholderConfigurer

open class PropertyPlaceholderConfigurer : PlaceholderConfigurerSupport

PlaceholderConfigurerSupport subclass that resolves ${...} placeholders against local properties and/or system properties and environment variables.

As of Spring 3.1, org.springframework.context.support.PropertySourcesPlaceholderConfigurer should be used preferentially over this implementation; it is more flexible through taking advantage of the org.springframework.core.env.Environment and org.springframework.core.env.PropertySource mechanisms also made available in Spring 3.1.

PropertyPlaceholderConfigurer is still appropriate for use when:

  • the spring-context module is not available (i.e., one is using Spring's BeanFactory API as opposed to ApplicationContext).
  • existing configuration makes use of the "systemPropertiesMode" and/or "systemPropertiesModeName" properties. Users are encouraged to move away from using these settings, and rather configure property source search order through the container's Environment; however, exact preservation of functionality may be maintained by continuing to use PropertyPlaceholderConfigurer.

Prior to Spring 3.1, the <context:property-placeholder/> namespace element registered an instance of PropertyPlaceholderConfigurer. It will still do so if using the spring-context-3.0.xsd definition of the namespace. That is, you can preserve registration of PropertyPlaceholderConfigurer through the namespace, even if using Spring 3.1; simply do not update your xsi:schemaLocation and continue using the 3.0 XSD.

ProviderCreatingFactoryBean

open class ProviderCreatingFactoryBean : AbstractFactoryBean<Provider<Any>>

A org.springframework.beans.factory.FactoryBean implementation that returns a value which is a JSR-330 javax.inject.Provider that in turn returns a bean sourced from a org.springframework.beans.factory.BeanFactory.

This is basically a JSR-330 compliant variant of Spring's good old ObjectFactoryCreatingFactoryBean. It can be used for traditional external dependency injection configuration that targets a property or constructor argument of type javax.inject.Provider, as an alternative to JSR-330's @Inject annotation-driven approach.

RuntimeBeanNameReference

open class RuntimeBeanNameReference : BeanReference

Immutable placeholder class used for a property value object when it's a reference to another bean name in the factory, to be resolved at runtime.

RuntimeBeanReference

open class RuntimeBeanReference : BeanReference

Immutable placeholder class used for a property value object when it's a reference to another bean in the factory, to be resolved at runtime.

ServiceLocatorFactoryBean

open class ServiceLocatorFactoryBean : FactoryBean<Any>, 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 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 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.

SetFactoryBean

open class SetFactoryBean : AbstractFactoryBean<MutableSet<Any>>

Simple factory for shared Set instances. Allows for central setup of Sets via the "set" element in XML bean definitions.

TypedStringValue

open class TypedStringValue : BeanMetadataElement

Holder for a typed String value. Can be added to bean definitions in order to explicitly specify a target type for a String value, for example for collection elements.

This holder will just store the String value and the target type. The actual conversion will be performed by the bean factory.

YamlMapFactoryBean

open class YamlMapFactoryBean : YamlProcessor, FactoryBean<MutableMap<String, Any>>, InitializingBean

Factory for a Map that reads from a YAML source, preserving the YAML-declared value types and their structure.

YAML is a nice human-readable format for configuration, and it has some useful hierarchical properties. It's more or less a superset of JSON, so it has a lot of similar features.

If multiple resources are provided the later ones will override entries in the earlier ones hierarchically; that is, all entries with the same nested key of type Map at any depth are merged. For example:

 foo: bar: one: two three: four 
plus (later in the list)
 foo: bar: one: 2 five: six 
results in an effective input of
 foo: bar: one: 2 three: four five: six 
Note that the value of "foo" in the first document is not simply replaced with the value in the second, but its nested values are merged.

YamlPropertiesFactoryBean

open class YamlPropertiesFactoryBean : YamlProcessor, FactoryBean<Properties>, InitializingBean

Factory for java.util.Properties that reads from a YAML source, exposing a flat structure of String property values.

YAML is a nice human-readable format for configuration, and it has some useful hierarchical properties. It's more or less a superset of JSON, so it has a lot of similar features.

Note: All exposed values are of type String for access through the common Properties#getProperty method (e.g. in configuration property resolution through PropertyResourceConfigurer#setProperties(Properties)). If this is not desirable, use YamlMapFactoryBean instead.

The Properties created by this factory have nested paths for hierarchical objects, so for instance this YAML

 environments: dev: url: http://dev.bar.com name: Developer Setup prod: url: http://foo.bar.com name: My Cool App 
is transformed into these properties:
 environments.dev.url=http://dev.bar.com environments.dev.name=Developer Setup environments.prod.url=http://foo.bar.com environments.prod.name=My Cool App 
Lists are split as property keys with [] dereferencers, for example this YAML:
 servers: - dev.bar.com - foo.bar.com 
becomes properties like this:
 servers[0]=dev.bar.com servers[1]=foo.bar.com