-
Notifications
You must be signed in to change notification settings - Fork 39
io microsphere spring beans factory DelegatingFactoryBean
Type: Class | Module: microsphere-spring-context | Package: io.microsphere.spring.beans.factory | Since: 1.0.0
A FactoryBean implementation that delegates to an existing object instance,
providing lifecycle management and integration with Spring's ApplicationContext.
This class is useful when you want to expose an already instantiated object as a Spring bean,
while still benefiting from Spring's lifecycle callbacks (e.g., InitializingBean,
DisposableBean, etc.).
- Delegates bean creation via the
#getObject()method. - Supports initialization through
InitializingBean#afterPropertiesSet(). - Supports destruction callback if the delegate implements
DisposableBean. - Implements Spring's aware interfaces such as
ApplicationContextAwareandBeanNameAware, delegating calls to the target object if applicable.
{@code
MyService myService = new MyServiceImpl();
DelegatingFactoryBean factoryBean = new DelegatingFactoryBean(myService);
// When used in a Spring configuration:
### Declaration
```java
public class DelegatingFactoryBean implements FactoryBean, InitializingBean, DisposableBean,
```
**Author:** Mercy
## Version Information
- **Introduced in:** `1.0.0`
- **Current Project Version:** `0.2.32-SNAPSHOT`
## Version Compatibility
This component is tested and compatible with the following Java versions:
| Java Version | Status |
|:---:|:---:|
| Java 17 | ✅ Compatible |
| Java 21 | ✅ Compatible |
| Java 25 | ✅ Compatible |
## Examples
```java
MyService myService = new MyServiceImpl();
DelegatingFactoryBean factoryBean = new DelegatingFactoryBean(myService);
// When used in a Spring configuration:
@Bean
public FactoryBean myServiceFactoryBean() {
return new DelegatingFactoryBean<>(myServiceInstance);
}
```
### Method Examples
#### `getObject`
```java
DisposableBean myBean = new MyDisposableBean();
DelegatingFactoryBean factoryBean = new DelegatingFactoryBean(myBean);
// factoryBean.isSingleton() returns true
// factoryBean.getObject() returns myBean
```
```java
User user = new User();
// Non-singleton: a new instance may be requested each time
DelegatingFactoryBean factoryBean = new DelegatingFactoryBean(user, false);
// factoryBean.isSingleton() returns false
// factoryBean.getObjectType() returns User.class
```
```java
User user = new User();
DelegatingFactoryBean factoryBean = new DelegatingFactoryBean(user, false);
Object obj = factoryBean.getObject();
// obj is the same instance as user
```
#### `getObjectType`
```java
User user = new User();
DelegatingFactoryBean factoryBean = new DelegatingFactoryBean(user, false);
Class> type = factoryBean.getObjectType();
// type is User.class
```
#### `afterPropertiesSet`
```java
DelegatingFactoryBean factoryBean = new DelegatingFactoryBean(myInitializingBean);
// Triggers delegate's afterPropertiesSet() if it implements InitializingBean
factoryBean.afterPropertiesSet();
```
#### `setApplicationContext`
```java
DelegatingFactoryBean factoryBean = new DelegatingFactoryBean(myBean);
// If myBean implements ApplicationContextAware, it will receive the context
factoryBean.setApplicationContext(applicationContext);
```
#### `setBeanName`
```java
DelegatingFactoryBean factoryBean = new DelegatingFactoryBean(myBean);
// If myBean implements BeanNameAware, it will receive the name "factoryBean"
factoryBean.setBeanName("factoryBean");
```
#### `isSingleton`
```java
DelegatingFactoryBean singletonBean = new DelegatingFactoryBean(delegate);
singletonBean.isSingleton(); // returns true (default)
DelegatingFactoryBean prototypeBean = new DelegatingFactoryBean(delegate, false);
prototypeBean.isSingleton(); // returns false
```
#### `destroy`
```java
DisposableBean disposable = new MyDisposableBean();
DelegatingFactoryBean factoryBean = new DelegatingFactoryBean(disposable);
// Invokes disposable.destroy()
factoryBean.destroy();
User user = new User();
DelegatingFactoryBean factoryBean2 = new DelegatingFactoryBean(user, false);
// No-op since User does not implement DisposableBean
factoryBean2.destroy();
```
## Usage
### Maven Dependency
Add the following dependency to your `pom.xml`:
```xml
io.github.microsphere-projects
microsphere-spring-context
${microsphere-spring.version}
```
> **Tip:** Use the BOM (`microsphere-spring-dependencies`) for consistent version management. See the [Getting Started](https://github.com/microsphere-projects/microsphere-spring#getting-started) guide.
### Import
```java
import io.microsphere.spring.beans.factory.DelegatingFactoryBean;
```
## API Reference
### Public Methods
| Method | Description |
|--------|-------------|
| `getObject` | Creates a new `DelegatingFactoryBean` that wraps the given delegate object |
| `getObjectType` | Returns the type of the delegate object. The type is resolved using |
| `afterPropertiesSet` | Invokes the `InitializingBean#afterPropertiesSet()` callback on the delegate |
| `setApplicationContext` | Sets the `ApplicationContext` and propagates it to the delegate if the delegate |
| `setBeanName` | Sets the bean name and propagates it to the delegate if the delegate implements |
| `isSingleton` | Returns whether this factory bean produces a singleton instance. The value is determined |
| `destroy` | Destroys the delegate by invoking its `DisposableBean#destroy()` method, |
### Method Details
#### `getObject`
```java
public Object getObject()
```
Creates a new `DelegatingFactoryBean` that wraps the given delegate object
as a singleton bean (the default).
### Example Usage
`DisposableBean myBean = new MyDisposableBean();
DelegatingFactoryBean factoryBean = new DelegatingFactoryBean(myBean);
// factoryBean.isSingleton() returns true
// factoryBean.getObject() returns myBean
`
public Class<?> getObjectType()
Returns the type of the delegate object. The type is resolved using
org.springframework.aop.support.AopUtils#getTargetClass(Object),
which correctly resolves the target class even for AOP proxies.
`User user = new User();
DelegatingFactoryBean factoryBean = new DelegatingFactoryBean(user, false);
Class type = factoryBean.getObjectType();
// type is User.class
`
public void afterPropertiesSet()
Invokes the InitializingBean#afterPropertiesSet() callback on the delegate
if it implements InitializingBean. This allows the delegate to perform
initialization work after all properties have been set by the containing
org.springframework.beans.factory.BeanFactory.
`DelegatingFactoryBean factoryBean = new DelegatingFactoryBean(myInitializingBean);
// Triggers delegate's afterPropertiesSet() if it implements InitializingBean
factoryBean.afterPropertiesSet();
`
public void setApplicationContext(ApplicationContext context)
Sets the ApplicationContext and propagates it to the delegate if the delegate
implements any Spring aware interfaces (e.g., ApplicationContextAware,
org.springframework.context.EnvironmentAware, etc.).
`DelegatingFactoryBean factoryBean = new DelegatingFactoryBean(myBean);
// If myBean implements ApplicationContextAware, it will receive the context
factoryBean.setApplicationContext(applicationContext);
`
public void setBeanName(String name)
Sets the bean name and propagates it to the delegate if the delegate implements
BeanNameAware.
`DelegatingFactoryBean factoryBean = new DelegatingFactoryBean(myBean);
// If myBean implements BeanNameAware, it will receive the name "factoryBean"
factoryBean.setBeanName("factoryBean");
`
public boolean isSingleton()
Returns whether this factory bean produces a singleton instance. The value is determined
by the singleton parameter passed to the constructor.
`DelegatingFactoryBean singletonBean = new DelegatingFactoryBean(delegate);
singletonBean.isSingleton(); // returns true (default)
DelegatingFactoryBean prototypeBean = new DelegatingFactoryBean(delegate, false);
prototypeBean.isSingleton(); // returns false
`
public void destroy()
Destroys the delegate by invoking its DisposableBean#destroy() method,
but only if the delegate implements DisposableBean. If the delegate does not
implement DisposableBean, this method is a no-op.
`DisposableBean disposable = new MyDisposableBean();
DelegatingFactoryBean factoryBean = new DelegatingFactoryBean(disposable);
// Invokes disposable.destroy()
factoryBean.destroy();
User user = new User();
DelegatingFactoryBean factoryBean2 = new DelegatingFactoryBean(user, false);
// No-op since User does not implement DisposableBean
factoryBean2.destroy();
`
FactoryBeanInitializingBeanDisposableBeanApplicationContextAwareBeanNameAware
This documentation was auto-generated from the source code of microsphere-spring.
spring-context
- AbstractInjectionPointDependencyResolver
- AbstractSmartLifecycle
- AbstractSpringResourceURLConnection
- AnnotatedBeanCapableImportBeanDefinitionRegistrar
- AnnotatedBeanCapableImportCandidate
- AnnotatedBeanCapableImportSelector
- AnnotatedBeanDefinitionRegistryUtils
- AnnotatedInjectionBeanPostProcessor
- AnnotatedInjectionPointDependencyResolver
- AnnotatedPropertySourceLoader
- AnnotationBeanDefinitionRegistryPostProcessor
- AnnotationUtils
- ApplicationContextUtils
- ApplicationEventInterceptor
- ApplicationEventInterceptorChain
- ApplicationListenerInterceptor
- ApplicationListenerInterceptorChain
- AutoRegistrationBean
- AutoRegistrationBeanInitializer
- AutoRegistrationBeanRegistrar
- AutowireCandidateResolvingListener
- AutowiredInjectionPointDependencyResolver
- BeanCapableImportCandidate
- BeanDefinitionUtils
- BeanDependencyResolver
- BeanFactoryListener
- BeanFactoryListenerAdapter
- BeanFactoryListeners
- BeanFactoryUtils
- BeanListener
- BeanListenerAdapter
- BeanListeners
- BeanMethodInjectionPointDependencyResolver
- BeanPropertyChangedEvent
- BeanRegistrar
- BeanSource
- BeanTimeStatistics
- BeanUtils
- CollectingConfigurationPropertyListener
- CompositeAutowireCandidateResolvingListener
- ConfigurableApplicationContextInitializer
- ConfigurationBeanAliasGenerator
- ConfigurationBeanBinder
- ConfigurationBeanBindingPostProcessor
- ConfigurationBeanBindingRegistrar
- ConfigurationBeanBindingsRegister
- ConfigurationBeanCustomizer
- ConfigurationPropertyOverrideAnnotationAttributesStrategy
- ConfigurationPropertyRepository
- ConstructionInjectionPointDependencyResolver
- ConversionServiceResolver
- ConversionServiceUtils
- DefaultApplicationEventInterceptorChain
- DefaultApplicationListenerInterceptorChain
- DefaultBeanDependencyResolver
- DefaultConfigurationBeanAliasGenerator
- DefaultConfigurationBeanBinder
- DefaultPropertiesPropertySource
- DefaultPropertiesPropertySourceLoader
- DefaultPropertiesPropertySources
- DefaultPropertiesPropertySourcesLoader
- DefaultResourceComparator
- DelegatingFactoryBean
- Dependency
- DependencyAnalysisBeanFactoryListener
- DependencyTreeWalker
- EnableAutoRegistrationBean
- EnableConfigurationBeanBinding
- EnableConfigurationBeanBindings
- EnableEventExtension
- EnableSpringConverterAdapter
- EnableSpringConverterAdapterRegistrar
- EnableTTLCaching
- EnvironmentEnabled
- EnvironmentListener
- EnvironmentUtils
- EventExtensionAttributes
- EventExtensionRegistrar
- EventPublishingBeanAfterProcessor
- EventPublishingBeanBeforeProcessor
- EventPublishingBeanInitializer
- ExposingClassPathBeanDefinitionScanner
- FilterMode
- GenericAnnotationAttributes
- GenericApplicationListenerAdapter
- GenericBeanNameGenerator
- GenericBeanPostProcessorAdapter
- HyphenAliasGenerator
- ImmutableMapPropertySource
- ImportOptional
- ImportOptionalSelector
- InjectionPointDependencyResolver
- InjectionPointDependencyResolvers
- InterceptingApplicationEventMulticaster
- InterceptingApplicationEventMulticasterProxy
- InterceptingApplicationListener
- JavaBeansPropertyChangeListenerAdapter
- JoinAliasGenerator
- JsonPropertySource
- JsonPropertySourceFactory
- ListenableAutowireCandidateResolver
- ListenableAutowireCandidateResolverInitializer
- ListenableConfigurableEnvironment
- ListenableConfigurableEnvironmentInitializer
- LoggingAutowireCandidateResolvingListener
- LoggingBeanFactoryListener
- LoggingBeanListener
- LoggingEnvironmentListener
- LoggingSmartLifecycle
- MethodParameterUtils
- MimeTypeUtils
- NamedBeanHolderComparator
- OnceApplicationContextEventListener
- OverrideAnnotationAttributes
- OverrideAnnotationAttributesStrategy
- ParallelPreInstantiationSingletonsBeanFactoryListener
- ProfileListener
- PropertiesUtils
- PropertyConstants
- PropertyResolverListener
- PropertyResolverUtils
- PropertySourceChangedEvent
- PropertySourceExtension
- PropertySourceExtensionAttributes
- PropertySourceExtensionLoader
- PropertySourcesChangedEvent
- PropertySourcesUtils
- PropertyValuesUtils
- ResolvableDependencyTypeFilter
- ResolvablePlaceholderAnnotationAttributes
- ResourceInjectionPointDependencyResolver
- ResourceLoaderUtils
- ResourcePropertySource
- ResourcePropertySourceLoader
- ResourcePropertySources
- ResourcePropertySourcesLoader
- ResourceUtils
- ResourceYamlProcessor
- SpringConverterAdapter
- SpringDelegatingBeanProtocolURLConnectionFactory
- SpringEnvironmentURLConnectionFactory
- SpringFactoriesLoaderUtils
- SpringProfilesURLConnectionAdapter
- SpringPropertySourcesURLConnectionAdapter
- SpringProtocolURLStreamHandler
- SpringResourceURLConnection
- SpringResourceURLConnectionAdapter
- SpringResourceURLConnectionFactory
- SpringSubProtocolURLConnectionFactory
- SpringVersion
- SpringVersionUtils
- TTLCachePut
- TTLCacheResolver
- TTLCacheable
- TTLCachingConfiguration
- TTLContext
- UnderScoreJoinAliasGenerator
- YamlPropertySource
- YamlPropertySourceFactory
spring-guice
spring-jdbc
- CompoundJdbcEventListenerFactory
- EnableP6DataSource
- NoOpP6LoadableOptions
- P6DataSourceBeanDefinitionRegistrar
- P6DataSourceBeanPostProcessor
- PropertySourcesP6LoadableOptionsAdapter
- SpringP6SpyURLConnectionFactory
spring-test
- AbstractWebFluxTest
- AbstractWebMvcTest
- AnnotatedTypeMetadataTestFactory
- EmbeddedDataBaseBeanDefinitionRegistrar
- EmbeddedDataBaseBeanDefinitionsRegistrar
- EmbeddedDatabaseType
- EmbeddedTomcatConfiguration
- EmbeddedTomcatContextLoader
- EmbeddedTomcatMergedContextConfiguration
- EmbeddedTomcatTestContextBootstrapper
- EmbeddedZookeeperServer
- EmbeddedZookeeperServerTestExecutionListener
- EnableEmbeddedDatabase
- EnableEmbeddedDatabases
- MockServletWebRequest
- PersonHandler
- PersonHandler
- RouterFunctionTestConfig
- RouterFunctionTestConfig
- ServletTestUtils
- SimpleUrlHandlerMappingTestConfig
- SimpleUrlHandlerMappingTestConfig
- SpringLoggingTest
- SpringTestUtils
- SpringTestWebUtils
- TestConditionContext
- TestController
- TestFilter
- TestFilterRegistration
- TestServlet
- TestServletContext
- TestServletContextListener
- TestServletRegistration
- User
- WebTestUtils
spring-web
- AbstractNameValueExpression
- AbstractWebEndpointMappingFactory
- AbstractWebRequestRule
- CompositeWebEndpointMappingRegistry
- CompositeWebRequestRule
- ConsumeMediaTypeExpression
- DelegatingHandlerMethodAdvice
- EnableWebExtension
- FilterRegistrationWebEndpointMappingFactory
- FilteringWebEndpointMappingRegistry
- GenericMediaTypeExpression
- HandlerMetadata
- HandlerMethodAdvice
- HandlerMethodArgumentInterceptor
- HandlerMethodArgumentsResolvedEvent
- HandlerMethodInterceptor
- HandlerMethodMetadata
- HttpUtils
- Jackson2WebEndpointMappingFactory
- MediaTypeExpression
- MediaTypeUtils
- NameValueExpression
- ProduceMediaTypeExpression
- PropertyConstants
- RegistrationWebEndpointMappingFactory
- RequestAttributesUtils
- RequestContextStrategy
- ServletRegistrationWebEndpointMappingFactory
- ServletWebEndpointMappingResolver
- SimpleWebEndpointMappingRegistry
- SmartWebEndpointMappingFactory
- SpringWebHelper
- SpringWebType
- UnknownSpringWebHelper
- WebEndpointMapping
- WebEndpointMappingFactory
- WebEndpointMappingFilter
- WebEndpointMappingRegistrar
- WebEndpointMappingRegistry
- WebEndpointMappingResolver
- WebEndpointMappingsReadyEvent
- WebEventPublisher
- WebExtensionBeanDefinitionRegistrar
- WebRequestConsumesRule
- WebRequestHeaderExpression
- WebRequestHeadersRule
- WebRequestMethodsRule
- WebRequestParamExpression
- WebRequestParamsRule
- WebRequestPattensRule
- WebRequestProducesRule
- WebRequestRule
- WebRequestUtils
- WebScope
- WebSource
- WebTarget
- WebType
- WebUtils
spring-webflux
- CompositeWebFilter
- ConsumingWebEndpointMappingAdapter
- DelegatingWebFilter
- EnableWebFluxExtension
- HandlerMappingWebEndpointMappingFactory
- HandlerMappingWebEndpointMappingResolver
- HandlerMetadataWebEndpointMappingFactory
- InterceptingHandlerMethodProcessor
- MonoUtils
- RequestContextWebFilter
- RequestHandledEventPublishingWebFilter
- RequestMappingMetadataWebEndpointMappingFactory
- RequestPredicateKind
- RequestPredicateVisitorAdapter
- ReversedProxyHandlerMapping
- RouterFunctionVisitorAdapter
- ServerRequestHandledEvent
- ServerWebRequest
- SpringWebFluxHelper
- StoringRequestBodyArgumentInterceptor
- StoringResponseBodyReturnValueInterceptor
- WebFluxExtensionBeanDefinitionRegistrar
- WebServerScope
- WebServerUtils
spring-webmvc
- AbstractPageRenderContextHandlerInterceptor
- AnnotatedMethodHandlerInterceptor
- ConfigurableContentNegotiationManagerWebMvcConfigurer
- ConsumingWebEndpointMappingAdapter
- ContentCachingFilter
- EnableWebMvcExtension
- EnableWebMvcExtensionListener
- ExclusiveViewResolverApplicationListener
- HandlerMappingWebEndpointMappingFactory
- HandlerMappingWebEndpointMappingResolver
- HandlerMetadataWebEndpointMappingFactory
- HandlerMethodArgumentResolverAdvice
- InterceptingHandlerMethodProcessor
- LazyCompositeHandlerInterceptor
- LoggingHandlerMethodArgumentResolverAdvice
- LoggingMethodHandlerInterceptor
- LoggingPageRenderContextHandlerInterceptor
- MethodHandlerInterceptor
- PropertyConstants
- RequestBodyAdviceAdapter
- RequestMappingMetadata
- RequestMappingMetadataWebEndpointMappingFactory
- RequestPredicateVisitorAdapter
- ResponseBodyAdviceAdapter
- ReversedProxyHandlerMapping
- RouterFunctionVisitorAdapter
- SpringWebMvcHelper
- StoringRequestBodyArgumentAdvice
- StoringResponseBodyReturnValueAdvice
- ViewResolverUtils
- ViewUtils
- WebMvcExtensionBeanDefinitionRegistrar
- WebMvcExtensionConfiguration
- WebMvcUtils
- WebUtils