Sweet.apex

  • Docs
  • Tutorials
Docs Menu
  • Sweet.apex Core
    • Transpilation
    • Grammar
    • Command
    • Config
  • Features
    • Action
    • Apex Doc
    • Array Creation
    • Aspect
    • Cast
    • Default Value
    • Enum
    • File
    • Function
    • Identity
    • Injection
    • Lambda
    • Log
    • Mod
    • Not Null
    • Operator
    • Optional
    • Reflection
    • Rethrow
    • Switch
    • Template String
    • Template
    • Script
    • Tagged String
    • Annotation
    • Nullable
    • Var
    • Val
    • Map Access
    • Constructor
    • Transaction
    • Destructure
    • Import Static
    • Pipeline
    • Varargs
    • Patch
    • Import As
  • Plugin Development
    • Feature
    • Test Case

Injection Guide

Injection

Feature Overview

This feature injects dependency. See DI(Dependency Injection) for more details.

Prerequisite

You need to configure the beans.json file should you want to use the named beans.

Sweet Apex Example

public class InjectDemo {
    @inject
    private Case c1;

    @inject('demo')
    private Case c2;
}

Transpiled Apex

public class InjectDemo {
    private Case c1 = (Case)Sweet.getBean(Case.class);
    private Case c2 = (Case)Sweet.getBean('demo');
}

Usage

@inject works for two scenarios.

  • Named Injections

To inject a named bean, you need to configure it in the beans.json like this:

[
    {
        "name": "demo",
        "type": "Case"
    }
]
  • Type Injections

To inject a typed bean, you need to bind the type first.

Sweet.bind(Case.class, Account.class); // Bind Case.class to be created by Account.class
Sweet.bindObject(Case.class, mockCase); // Bind Case.class to a created object

If no bindings are found, the original type will be used to create the instance.

Contribute on Github! Edit this section.