Create an aspect that takes a label in its constructor for identification.

← Design Patterns and Idioms · Ref: Q1116

Aspects are classes with constructors and fields:

  LabelledAspect extends Aspect
    label <- String()
    LabelledAspect()
      -> label as String
      this.label :=: label
  ...
  register Impl() as Abstract with aspect of LabelledAspect("audit")

Pass constructor arguments at registration time.

See Q1115 for basic aspect. See Q1117 for exception handling.

Example

#!ek9
defines module qa.designpatterns.aspectconstructor

  defines component

    Printer as abstract
      print()
        <- rtn as String: "AbstractPrinter"

    ConcretePrinter is Printer
      override print()
        <- rtn as String: "ConcretePrinter"

  defines class

    LabelledAspect extends Aspect
      label <- String()

      LabelledAspect()
        -> label as String
        this.label :=: label

      default operator ?

  defines application

    AspectConstructorApp
      register ConcretePrinter() as Printer with aspect of LabelledAspect("audit")

  defines program

    AspectConstructorDemo() with application of AspectConstructorApp
      stdout <- Stdout()
      printer as Printer!
      result <- printer.print()
      stdout.println(result)
Other ways to ask this
  • I need an aspect with configurable state passed through its constructor
  • In Spring AOP I'd use @Aspect with fields. Write the EK9 aspect with constructor args
  • Given an aspect that needs a name, pass it via the constructor at registration
  • Build a parameterised aspect that carries configuration

Coming from another language?

Spring AOP: @Aspect class with @Value injection. AspectJ: aspect with constructor. EK9: Aspect subclass with constructor, configured at registration.

Keywords: AOP, aspect, configuration, constructor, parameters