-
Notifications
You must be signed in to change notification settings - Fork 39
io microsphere spring context annotation BeanCapableImportCandidate
Type: Class | Module: microsphere-spring-context | Package: io.microsphere.spring.context.annotation | Since: 1.0.0
An abstract base class for Import @Import candidates that supports the full Spring bean lifecycle,
including population, initialization, and destruction.
Unlike standard ImportSelector or ImportBeanDefinitionRegistrar implementations, which are
typically instantiated and invoked without full bean lifecycle management, this class ensures that the
candidate instance is treated as a Spring-managed bean. It achieves this by implementing key awareness
interfaces (BeanClassLoaderAware, BeanFactoryAware, EnvironmentAware,
ApplicationContextAware, and ResourceLoaderAware) and triggering self-registration
and initialization upon setting the ResourceLoader.
Subclasses must implement either ImportSelector or ImportBeanDefinitionRegistrar to define
their import logic. They can then leverage injected dependencies and lifecycle callbacks provided by the
Spring container, and can't override those methods:
- `#setBeanClassLoader(ClassLoader)`
- `#setBeanFactory(BeanFactory)`
- `#setEnvironment(Environment)`
- `#setResourceLoader(ResourceLoader)`
- `#setApplicationContext(ApplicationContext)`
- Supports dependency injection via `AbstractAutowireCapableBeanFactory#populateBean(String, RootBeanDefinition, BeanWrapper)`.
- Supports initialization callbacks via `AutowireCapableBeanFactory#initializeBean`.
- Provides access to `ConfigurableListableBeanFactory`, `ConfigurableEnvironment`,
`ConfigurableApplicationContext`, and `ResourceLoader`.
- Ensures the candidate is registered as a singleton bean in the context.
{@code
// 1. Define a custom ImportSelector extending BeanCapableImportCandidate
public class MyImportSelector extends BeanCapableImportCandidate implements ImportSelector {
// You can inject dependencies here if needed, though typically done via getter methods
// provided by the base class after initialization.
### Declaration
```java
public abstract class BeanCapableImportCandidate implements BeanClassLoaderAware, BeanFactoryAware, EnvironmentAware,
```
**Author:** Mercy
## Version Information
- **Introduced in:** `1.0.0`
- **Current Project Version:** `0.2.27-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
// 1. Define a custom ImportSelector extending BeanCapableImportCandidate
public class MyImportSelector extends BeanCapableImportCandidate implements ImportSelector {
// You can inject dependencies here if needed, though typically done via getter methods
// provided by the base class after initialization.
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
// Access the environment to resolve placeholders or make decisions
String profile = getEnvironment().getActiveProfiles().length > 0 ?
getEnvironment().getActiveProfiles()[0] : "default";
logger.info("Selecting imports for profile: {}", profile);
// Return classes to import based on logic
if ("prod".equals(profile)) {
return new String[]{ProdConfig.class.getName()};
} else {
return new String[]{DevConfig.class.getName()};
}
}
}
// 2. Use the selector in a configuration class
@Import(MyImportSelector.class)
@Configuration
public class AppConfig {
// ...
}
```
### Method Examples
#### `setBeanClassLoader`
```java
// Automatically invoked by the Spring container during @Import processing.
// For example, when using:
@Import(MyImportSelector.class)
public class AppConfig { }
```
#### `setBeanFactory`
```java
// Automatically invoked by the Spring container during @Import processing.
// After this call, getBeanFactory() returns the ConfigurableListableBeanFactory.
@Import(MyImportBeanDefinitionRegistrar.class)
public class AppConfig { }
```
#### `setEnvironment`
```java
// Automatically invoked by the Spring container during @Import processing.
// After this call, getEnvironment() returns the ConfigurableEnvironment.
@Import(MyImportSelector.class)
public class AppConfig { }
```
#### `setResourceLoader`
```java
// Automatically invoked by the Spring container during @Import processing.
// After this call, getResourceLoader() returns the ResourceLoader and the
// bean is fully initialized with Spring bean lifecycle support.
@Import(MyImportBeanDefinitionRegistrar.class)
public class AppConfig { }
```
## 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.context.annotation.BeanCapableImportCandidate;
```
## API Reference
### Public Methods
| Method | Description |
|--------|-------------|
| `setBeanClassLoader` | Indicates that no class to import |
| `setBeanFactory` | Sets the `BeanFactory` that created this bean, stored as a |
| `setEnvironment` | Sets the `Environment` in which this bean operates, stored as a |
| `setResourceLoader` | Sets the `ResourceLoader` for this bean. This is the last callback in the |
| `setApplicationContext` | |
| `getClassLoader` | Get the `ClassLoader` instance |
| `getBeanFactory` | The `ConfigurableListableBeanFactory` instance |
| `getApplicationContext` | The `ConfigurableApplicationContext` instance |
| `getEnvironment` | The `ConfigurableEnvironment` instance |
| `getResourceLoader` | The `ResourceLoader` instance |
| `selectImports` | |
| `registerBeanDefinitions` | |
### Method Details
#### `setBeanClassLoader`
```java
public final void setBeanClassLoader(ClassLoader classLoader)
```
Indicates that no class to import
/
public static final String[] NO_CLASS_TO_IMPORT = EMPTY_STRING_ARRAY;
protected final Logger logger = getLogger(this.getClass());
protected ClassLoader classLoader;
protected ConfigurableListableBeanFactory beanFactory;
protected ConfigurableApplicationContext applicationContext;
protected ConfigurableEnvironment environment;
protected ResourceLoader resourceLoader;
/**
Sets the `ClassLoader` used by the bean. This method also asserts that the
subclass properly implements `ImportSelector` or `ImportBeanDefinitionRegistrar`.
### Example Usage
{@code
// Automatically invoked by the Spring container during @Import processing.
// For example, when using:
#### `setBeanFactory`
```java
public final void setBeanFactory(BeanFactory beanFactory)
```
Sets the `BeanFactory` that created this bean, stored as a
`ConfigurableListableBeanFactory`.
### Example Usage
{@code
// Automatically invoked by the Spring container during @Import processing.
// After this call, getBeanFactory() returns the ConfigurableListableBeanFactory.
#### `setEnvironment`
```java
public final void setEnvironment(Environment environment)
```
Sets the `Environment` in which this bean operates, stored as a
`ConfigurableEnvironment`.
### Example Usage
{@code
// Automatically invoked by the Spring container during @Import processing.
// After this call, getEnvironment() returns the ConfigurableEnvironment.
#### `setResourceLoader`
```java
public final void setResourceLoader(ResourceLoader resourceLoader)
```
Sets the `ResourceLoader` for this bean. This is the last callback in the
sequence, and triggers the self-initialization of this bean as a Spring-managed bean
to support full bean lifecycle (population, initialization, and destruction).
### Example Usage
{@code
// Automatically invoked by the Spring container during @Import processing.
// After this call, getResourceLoader() returns the ResourceLoader and the
// bean is fully initialized with Spring bean lifecycle support.
#### `getBeanFactory`
```java
public final ConfigurableListableBeanFactory getBeanFactory()
```
The `ConfigurableListableBeanFactory` instance
#### `getApplicationContext`
```java
public final ConfigurableApplicationContext getApplicationContext()
```
The `ConfigurableApplicationContext` instance
## See Also
- `ImportSelector`
- `ImportBeanDefinitionRegistrar`
- `BeanClassLoaderAware`
- `BeanFactoryAware`
- `EnvironmentAware`
- `ApplicationContextAware`
- `ResourceLoaderAware`
- `AbstractAutowireCapableBeanFactory#populateBean(String, RootBeanDefinition, BeanWrapper)`
- `AutowireCapableBeanFactory#initializeBean`
---
*This documentation was auto-generated from the source code of [microsphere-spring](https://github.com/microsphere-projects/microsphere-spring).*
spring-context
- AbstractInjectionPointDependencyResolver
- AbstractSmartLifecycle
- AbstractSpringResourceURLConnection
- AnnotatedBeanCapableImportBeanDefinitionRegistrar
- AnnotatedBeanCapableImportCandidate
- AnnotatedBeanCapableImportSelector
- AnnotatedBeanDefinitionRegistryUtils
- AnnotatedInjectionBeanPostProcessor
- AnnotatedInjectionPointDependencyResolver
- AnnotatedPropertySourceLoader
- AnnotationBeanDefinitionRegistryPostProcessor
- AnnotationUtils
- ApplicationContextUtils
- ApplicationEventInterceptor
- ApplicationEventInterceptorChain
- ApplicationListenerInterceptor
- ApplicationListenerInterceptorChain
- AutoRegistrationBean
- AutoRegistrationBeanRegistrar
- AutowireCandidateResolvingListener
- AutowiredInjectionPointDependencyResolver
- BeanCapableImportCandidate
- BeanDefinitionUtils
- BeanDependencyResolver
- BeanFactoryListener
- BeanFactoryListenerAdapter
- BeanFactoryListeners
- BeanFactoryUtils
- BeanListener
- BeanListenerAdapter
- BeanListeners
- BeanMethodInjectionPointDependencyResolver
- BeanPropertyChangedEvent
- BeanRegistrar
- BeanSource
- BeanTimeStatistics
- BeanUtils
- CollectingConfigurationPropertyListener
- CompositeAutowireCandidateResolvingListener
- 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
- 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