#[derive(Component)]
{
// Attributes available to this derive:
#[component]
#[autowired]
}
Expand description
Derive macro for automatic component registration and dependency injection
The Component derive macro automatically implements the ComponentInitializer trait
and registers the component with the IoC container. It handles dependency injection
for fields marked with #[autowired] and provides sensible defaults for other fields.
§Attributes
#[autowired]- Marks a field for automatic dependency injection. The field must be of typeArc<T>#[component(scope = "...")]- Sets the component scope (defaults toSingleton)
§Field Initialization Rules
- Autowired fields: Automatically injected by the container
- Option fields: Initialized to
None - Other fields: Initialized using
Default::default()
§Examples
use verdure::Component;
use std::sync::Arc;
// Simple component with no dependencies
#[derive(Component)]
struct ConfigService {
config_path: String, // Will be initialized with Default::default() = ""
port: u16, // Will be initialized with Default::default() = 0
}
// Component with dependencies
#[derive(Component)]
struct DatabaseService {
#[autowired]
config: Arc<ConfigService>, // Automatically injected
optional_cache: Option<String>, // Initialized to None
connection_pool_size: usize, // Default::default() = 0
}
// Component with custom scope
#[derive(Component)]
#[component(scope = "Prototype")]
struct RequestHandler {
#[autowired]
db: Arc<DatabaseService>,
request_id: String,
}§Generated Code
The macro generates implementations of ComponentInitializer and registers the component
with the global registry using the inventory crate.
§Panics
The macro will produce compile-time errors in the following cases:
- Applying to enums or unions (only structs with named fields are supported)
- Using
#[autowired]on fields that are notArc<T> - Invalid syntax in component attributes