Mechanisms

ActivityContext: The Heart of the Aspectran Container

ActivityContext is the heart of the Aspectran framework and the top-level IoC/DI (Inversion of Control & Dependency Injection) container governing all application components.

Unlike traditional framework containers that focus solely on object (Bean) lifecycles and dependency injection, Aspectran’s ActivityContext is a central orchestrator that seamlessly integrates and controls metadata and runtime execution for all framework subsystems: Bean Registry, Translets, Aspects, Schedules, Template Renderers, Type Converters, Async Task Executors, and Internationalized Message Sources.

1. Structural Position and Interface Contract of ActivityContext

ActivityContext defines the standard interface contract, while DefaultActivityContext acts as the primary concrete implementation inside the framework.

classDiagram
    direction TB
    class Component {
        <<interface>>
        +initialize()
        +destroy()
        +isAvailable() boolean
        +isInitializable() boolean
        +isInitialized() boolean
        +isDestroyed() boolean
        +getComponentName() String
    }
    class AbstractComponent {
        <<abstract>>
        #doInitialize()*
        #doDestroy()*
        #checkInitializable()
        #checkNotDestroyed()
    }
    class ActivityContext {
        <<interface>>
        +getName() String
        +getMasterService() CoreService
        +getApplicationAdapter() ApplicationAdapter
        +getClassLoader() ClassLoader
        +getEnvironment() Environment
        +getBeanRegistry() BeanRegistry
        +getAspectRuleRegistry() AspectRuleRegistry
        +getTransletRuleRegistry() TransletRuleRegistry
        +getScheduleRuleRegistry() ScheduleRuleRegistry
        +getTypeConverterRegistry() TypeConverterRegistry
        +getTemplateRenderer() TemplateRenderer
        +getMessageSource() MessageSource
        +getEventPublisher() EventPublisher
        +getAsyncTaskExecutor() AsyncTaskExecutor
        +getCurrentActivity() Activity
        +getAvailableActivity() Activity
        +getDefaultActivity() Activity
    }
    class DefaultActivityContext {
        -ThreadLocal~Activity~ currentActivityHolder
        -CounterStatistic activityCounter
        -Activity defaultActivity
        -DefaultBeanRegistry beanRegistry
        -AspectRuleRegistry aspectRuleRegistry
        -ScheduleRuleRegistry scheduleRuleRegistry
        -TransletRuleRegistry transletRuleRegistry
        -DefaultTemplateRenderer templateRenderer
        #doInitialize()
        #doDestroy()
    }

    Component <|.. AbstractComponent
    AbstractComponent <|-- DefaultActivityContext
    ActivityContext <|.. DefaultActivityContext

Core Contracts & Inheritance Structure

  • Compliance with the Component Contract: DefaultActivityContext extends AbstractComponent, incorporating a strict lifecycle state machine. Invalid access while uninitialized or after destruction is immediately blocked with explicit exceptions.
  • Bi-directional Binding with Master Service (CoreService): The context maintains a reference to its owning top-level service instance via getMasterService(), ensuring tight coordination with host environments and lifecycle managers.

2. Nine Core Subsystems and Registries

ActivityContext unifies and manages nine essential subsystems that sustain the application.

graph TD
    AC[DefaultActivityContext]

    subgraph Registries["Core Registry Layer"]
        BR[BeanRegistry<br/>POJO bean instantiation, DI, lifecycle management]
        AR[AspectRuleRegistry<br/>AOP joinpoint & advice mapping]
        TR[TransletRuleRegistry<br/>Request routing, path variables, action pipelines]
        SR[ScheduleRuleRegistry<br/>Quartz jobs & trigger rules management]
        TCR[TypeConverterRegistry<br/>Data type conversion & formatting]
    end

    subgraph Services["Execution & Infrastructure Service Layer"]
        ENV[Environment<br/>Active profiles, properties, encryption context]
        TRnd[TemplateRenderer<br/>Pebble, FreeMarker, Thymeleaf view rendering]
        MS[MessageSource<br/>Internationalized i18n message bundles]
        EP[EventPublisher<br/>Component event broadcasting & listener dispatching]
        ATE[AsyncTaskExecutor<br/>Asynchronous background thread pool execution]
    end

    AC --> BR
    AC --> AR
    AC --> TR
    AC --> SR
    AC --> TCR
    AC --> ENV
    AC --> TRnd
    AC --> MS
    AC --> EP
    AC --> ATE

1) Bean Management Subsystem: BeanRegistry

  • Stores metadata (BeanRule) for all objects defined via XML, APON, or Java annotations (@Component, @Bean, @Autowired).
  • Manages diverse lifecycle scopes: Singleton, Prototype, Request, and Session.
  • Supports constructor injection, field injection, and setter injection, while fundamentally preventing runtime dependency errors through bootstrap circular reference inspection (BeanReferenceInspector).
  • Executes initialization (@Initialize, InitializableBean) and destruction callbacks (@Destroy, DisposableBean).

2) AOP Subsystem: AspectRuleRegistry

  • Indexes and retains declared aspect rules (AspectRule).
  • Instantly matches joinpoints (before, after, thrown, finally) to determine which advice methods to invoke when specific translets or bean methods are called.

3) Request Routing Subsystem: TransletRuleRegistry

  • Manages translet rules (TransletRule), the primary units of execution in Aspectran.
  • Evaluates RESTful URI patterns (e.g., /users/{id}), wildcard patterns (e.g., /order/**), and HTTP method constraints to perform high-speed routing.

4) Scheduling Subsystem: ScheduleRuleRegistry

  • Manages scheduled task definitions (ScheduleRule) driven by Cron expressions or interval triggers, supplying schedule metadata to the subordinate SchedulerService.

5) Type Conversion Subsystem: TypeConverterRegistry

  • Maintains a registry of converters capable of safely transforming string request parameters into Java primitives, dates, collections, or custom Enums.

6) View Template Rendering Subsystem: TemplateRenderer

  • A standardized component facilitating integrated rendering across diverse template engines including Pebble, FreeMarker, Thymeleaf, and JSP.

7) Internationalization (i18n) Subsystem: MessageSource

  • Dynamically resolves internationalized messages according to the client’s Locale.
  • Automatically instantiates and delegates to a default DelegatingMessageSource when no explicit messageSource bean is defined.

8) Event Subsystem: EventPublisher

  • Provides event broadcasting and listener dispatching mechanisms for decoupled inter-component communication across the application.

9) Asynchronous Subsystem: AsyncTaskExecutor

  • Execution engine supporting concurrent, parallel execution of asynchronous background tasks across managed thread pools.

3. Component Lifecycle State Machine and Initialization/Destruction Pipelines

DefaultActivityContext enforces a deterministic two-stage lifecycle pipeline to guarantee consistency across all managed components during startup and teardown.

stateDiagram-v2
    [*] --> Uninitialized: Instance created (new DefaultActivityContext)
    Uninitialized --> Initializing: initialize() invoked (checkInitializable passes)
    Initializing --> Initialized: doInitialize() succeeds
    Initialized --> Available: Service ready (isAvailable() == true)
    Available --> Destroying: destroy() invoked
    Destroying --> Destroyed: doDestroy() completes (resources cleaned up)
    Destroyed --> [*]

Initialization Pipeline (doInitialize)

When initialize() is invoked on the context, the following steps execute sequentially within an isolated thread context classloader (ThreadContextHelper.runThrowable) environment:

  1. Pre-Validation: Asserts (Assert.state) that all mandatory registries (beanRegistry, aspectRuleRegistry, scheduleRuleRegistry, transletRuleRegistry, templateRenderer) are fully configured.
  2. Type Converter Initialization: typeConverterRegistry.initialize()
  3. Bean Registry Initialization: beanRegistry.initialize()
    • Instantiates singleton-scoped beans using constructor injection.
    • Injects field and setter dependencies.
    • Invokes @Initialize or InitializableBean.initialize() callbacks.
  4. Aspect & Rule Registries Initialization:
    • aspectRuleRegistry.initialize(): Pre-compiles pointcut expressions and constructs lookup indexes.
    • scheduleRuleRegistry.initialize(): Activates schedule job rules.
    • transletRuleRegistry.initialize(): Optimizes request routing trees.
  5. Template Renderer Initialization: templateRenderer.initialize()
  6. MessageSource Resolution:
    • Locates any bean registered under the ID messageSource. If absent, instantiates a default DelegatingMessageSource.
  7. Event Publisher Configuration: Creates DefaultEventPublisher integrated with the bean event listener registry.

Destruction Pipeline (doDestroy)

During application shutdown, resources are safely released in reverse order of initialization:

  1. Asynchronous Task Termination: If an active AsyncTaskExecutor exists, gracefully concludes pending jobs and closes it (AutoCloseable.close()).
  2. Event Listener Unregistration: Cleans up all registered event listeners.
  3. Bean Instance Teardown: Invokes destruction callbacks (@Destroy, DisposableBean.destroy()) on singleton beans and clears internal caches.
  4. Registry & Renderer Teardown in Reverse Order: Successively tears down and frees memory for templateRenderer, transletRuleRegistry, scheduleRuleRegistry, aspectRuleRegistry, and typeConverterRegistry.

4. Multi-Threaded Request Isolation and Activity Management

In high-concurrency environments such as web applications, multiple concurrent client requests access the same ActivityContext simultaneously. The context provides the following activity management structure to maintain strict thread safety while isolating request execution states:

ThreadLocal-Based Isolation

  • currentActivityHolder: Isolates and retains the Activity instance currently being processed by the executing thread in thread-local storage.
  • Three-Tier Activity Resolution Strategy:
  • Real-Time Active Request Metering (CounterStatistic): The internal activityCounter monitors the total number of actively executing activities in real time, supporting graceful shutdown workflows and busy-state queries (isBusy()).

5. Aware Interface Infrastructure for Dependency Injection

POJO beans managed by the Aspectran IoC container can directly receive core framework infrastructure objects by implementing specific *Aware interfaces:

Aware InterfaceInjected ObjectInjection Timing & Purpose
ActivityContextAwareActivityContextInjects the entire context immediately after bean creation
CurrentActivityAwareActivityInjects the executing thread’s active activity at request processing time
EnvironmentAwareEnvironmentInjects the environment object for profile and property resolution
ApplicationAdapterAwareApplicationAdapterInjects host environment adapters such as ServletContext
ClassLoaderAwareClassLoaderInjects the dedicated classloader used by the context

🔍 Related Detailed Mechanisms

6. Next Steps: Exploring Detailed Mechanisms

To explore how the ActivityContext is assembled from configuration files, scanned annotations, and internal parsers, refer to the ActivityContext Building Process guide.

To inspect how all mechanisms and packages interconnect across the entire framework, refer to the Aspectran Detailed Mechanisms Index.