{"id":19177011,"url":"https://github.com/joomcode/lightsaber","last_synced_at":"2025-05-07T20:09:38.386Z","repository":{"id":34129693,"uuid":"170310869","full_name":"joomcode/lightsaber","owner":"joomcode","description":"Compile time dependency injection framework for JVM languages. Especially for Kotlin.","archived":false,"fork":false,"pushed_at":"2023-10-02T18:23:21.000Z","size":2671,"stargazers_count":15,"open_issues_count":3,"forks_count":0,"subscribers_count":75,"default_branch":"develop","last_synced_at":"2025-05-07T20:09:30.110Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Kotlin","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/joomcode.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-02-12T12:02:17.000Z","updated_at":"2023-12-29T19:40:46.000Z","dependencies_parsed_at":"2024-11-09T10:33:12.178Z","dependency_job_id":"0dbd681a-006b-4b7c-969c-d79ef9eacf66","html_url":"https://github.com/joomcode/lightsaber","commit_stats":null,"previous_names":[],"tags_count":53,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joomcode%2Flightsaber","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joomcode%2Flightsaber/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joomcode%2Flightsaber/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joomcode%2Flightsaber/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/joomcode","download_url":"https://codeload.github.com/joomcode/lightsaber/tar.gz/refs/heads/develop","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252949271,"owners_count":21830151,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-09T10:31:35.603Z","updated_at":"2025-05-07T20:09:38.343Z","avatar_url":"https://github.com/joomcode.png","language":"Kotlin","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![Build](https://github.com/joomcode/lightsaber/workflows/Build/badge.svg)](https://github.com/joomcode/lightsaber/actions)\n\nLightsaber\n==========\n\nCompile time dependency injection framework for JVM languages. Especially for Kotlin.\n\nWhy?\n----\n\nThis framework is inspired by two projects: Guice and Dagger. While Guice is a quite small but a very powerful library\nit's not efficient enough on Android as it relies on reflection at runtime. On the other hand Dagger makes all\nits magic at compile time and thus is very efficient. However, Dagger uses APT under the hood, what may become a problem\nwhen used not from Java.\n\nThe goal of Lightsaber is to provide lightning-fast compile time dependency injection and not to rely on APT at the same\ntime so that the library can be used with almost any JVM language and on Android.\n\nUsage\n-----\n\n### Configuration\n\n```groovy\nbuildscript {\n  repositories {\n    mavenCentral()\n  }\n\n  dependencies {\n    classpath 'com.joom.lightsaber:lightsaber-gradle-plugin:1.0.0-alpha15'\n  }\n}\n\n// For Android projects.\napply plugin: 'com.android.application'\napply plugin: 'com.joom.lightsaber.android'\n\n// For other projects.\napply plugin: 'java'\napply plugin: 'com.joom.lightsaber'\n\n// Optional, just if you need Kotlin extension functions.\ndependencies {\n  implementation 'com.joom.lightsaber:lightsaber-core-kotlin:1.0.0-alpha15'\n}\n```\n\nAndroid projects that use Android Gradle Plugin \u003e= 7.1.0 must apply `com.joom.lightsaber.adroid` plugin to every Gradle module, that uses Lightsaber and to the `application` module as well. Android projects that use older Android Gradle Plugin versions should apply `com.joom.lightsaber.adroid` plugin to `application` module only.\n\n### Declaring dependencies\n\nThe primary goal of a DI framework is to inject dependencies into your code. Lightsaber can do that with constructor,\nfield, and method injection. In order to make injection work you have to annotate a method or a field with the `@Inject`\nannotation and [provide dependencies](#providing-dependencies) in other parts of the project.\n\n#### Constructor injection\n\nConstructor injection is the most proper way of performing injection. All you have to do is to annotate a constructor of\na class with `@Inject`. Lightsaber will be able to provide values for the arguments of the constructor and to create\nan instance of the class using this constructor. Moreover, when using constructor injection the class becomes eligible\nfor provision, that is this class itself can be used as a dependency. Lightsaber requires neither the class, nor the\ninjectable constructor to be `public`.\n\n```java\npublic class Droid {\n  @Inject\n  public Droid(Battery battery) {\n  }\n}\n```\n\n#### Field injection\n\nSometimes you don't manage instantiation of a class. In this case you cannot use constructor injection. But you can\nstill use dependency injection for such classes. The easiest way to do that is to inject dependencies right into fields\nof your class. To inform Lightsaber which fields it needs to inject you have to annotate them with `@Inject`.\nAgain, Lightsaber doesn't require the injectable field to be `public` or `final`.\n\n```java\npublic class Droid {\n  @Inject\n  private Battery battery;\n}\n```\n\n#### Method injection\n\nIn some cases you may want Lightsaber to call a method of a class after all fields of the class have been injected.\nJust annotate the method with `@Inject` and Lightsaber will provide values for the arguments of the method and invoke\nit. And as always, Lightsaber doesn't need the method to be `public`.\n\n```java\npublic class Droid {\n  private Battery battery;\n\n  @Inject\n  public void setBattery(Battery battery) {\n    this.battery = battery;\n  }\n}\n```\n\n#### Injection order\n\nLet's assume there's a class with constructor, fields, and methods marked as injectable . This class may have ancestor\nclasses with injectable fields and methods. When instantiating this class Lightsaber will perform injection in the\nfollowing order.\n\n1. Instantiate the class via its injectable constructor.\n2. Inject fields starting from ancestor classes.\n3. Invoke injectable methods starting from ancestor classes. The order of injectable method invocations is undefined.\n\n### Contracts\n\nA contract is an interface that may contain any number of methods and can extend other interfaces which act as a typed dependency provider.\nContract's methods must have no arguments and must return a non-`void` type.\n\n```java\npublic interface DroidContract {\n  Droid getDroid();\n}\n```\n\nWhen the contract is provided by a container this container must also provide dependencies returned\nby every method of the contract. If at least one dependency isn't provided the compilation will\nfail. Contract instances created by Lightsaber don't actually hold any dependencies. Instead every\ncontract's method just delegates to the container, which means that contract's dependencies aren't\ninstantiated when the contract instance is created.\n\nThere're two ways to create a contract. The first way is to annotate the contract interface\nwith `@Contract` and\n`@ProvidedBy` annotations. In this case the contract will be provided from a module just like any\nother dependency.\n\n```java\n\n@Module\npublic class DroidModule {\n    @Provide\n    public Droid provideDroid() {\n        return new Droid();\n    }\n}\n\n@Contract\n@ProvidedBy(DroidModule.class)\npublic interface DroidContract {\n    Droid getDroid();\n}\n```\n\nBut this approach requires annotating the contract interface so it cannot be used with the interface you don't control.\nMoreover, you'll need to retrieve the contract somehow.\n \nLuckily there's the second, more type safe way to create the contract. You can define a `ContractConfiguration` for this\ncontract and then get an instance of the contract from `Lightsaber`. \n\n```java\npublic class DroidContractConfiguration extends ContractConfiguration\u003cDroidContract\u003e {\n  @Provide\n  public Droid provideDroid() {\n    return new Droid();\n  }\n}\n\nLightsaber lightsaber = new Lightsaber.Builder().build(); \nDroidContract contract = lightsaber.createContract(new DroidContractConfiguration());\n```\n\nThe only thing `ContractConfiguration` is different from modules (see [modules](#modules) for more details) is that is should extend from\n`ContractConfiguration` instead of being annotated with some annotation. Meaning to say it can\nprovide dependencies, import modules, and do other stuff.\n\nContracts can be used not just for accessing dependencies in a statically typed way but also for\nproviding dependencies to modules, and other contracts' configurations. In order to do that you just\nhave to add a method that returns a contract instance and to annotate this method with `@Import`\nand `@Contract` annotations. In this case all the dependencies provided by the contract will be\nimported to the container.\n\n```java\npublic interface DroidPartsContract {\n    Battery getBattery();\n\n    MemoryCore getMemoryCore();\n}\n\npublic interface DroidContract {\n    Droid droid;\n}\n\npublic class DroidContractConfiguration extends ContractConfiguration\u003cDroidContract\u003e {\n    @Import\n    @Contract\n    private final DroidPartsContract droidPartsContract;\n\n    public DroidContractConfiguration(final DroidPartsContract droidPartsContract) {\n        this.droidPartsContract = droidPartsContract;\n    }\n\n    @Provide\n    public Droid provideDroid(final Battery battery, final MemoryCore memoryCore) {\n        return new Droid(battery, memoryCore);\n    }\n}\n``` \n\nAlso, imported contracts can be wrapped with `com.joom.lightsaber.Lazy` or `kotlin.Lazy`. In this case, the contract will be instantiated only when some of its dependencies would need. It can reduce `ContractConfiguration` creation time, especially for contracts with many dependencies. \n\n```java\npublic class DroidContractConfiguration extends ContractConfiguration\u003cDroidContract\u003e {\n    @Import\n    @Contract\n    private final Lazy\u003cDroidPartsContract\u003e droidPartsContract;\n\n    public DroidContractConfiguration(final Lazy\u003cDroidPartsContract\u003e droidPartsContract) {\n        this.droidPartsContract = droidPartsContract;\n    }\n\n    @Provide\n    public Droid provideDroid(final Battery battery, final MemoryCore memoryCore) {\n        return new Droid(battery, memoryCore);\n    }\n}\n```\n\n### Providing dependencies\n\nIn order to be able to inject a dependency you have to provide this dependency first. In other words you have to tell\nLightsaber what it have to return when requested a dependency of some type. This can be done in three ways: using contracts,\nusing modules and their provider methods, via injectable constructors mentioned earlier, and by using the `@ProvidedAs`\nannotation.\n\n#### Provider methods\n\nLightsaber requires provider methods to be defined in modules that need to be combined into contracts configurations.\n\n##### Modules\n\nA module is a logical unit responsible for providing dependencies belonging to the module. Module classes must be\nannotated with the `@Module` annotation. A module can contain a number of provider methods. Lightsaber treats a method\nas a provider method if it's annotated with the `@Provide` annotation. When a type is provided by a provider method\nit can be injected into a class in other parts of the project. Neither the module nor its provider methods are required\nto be `public`.\n\n```java\n@Module\npublic class DroidModule {\n  @Provide\n  public Droid provideDroid() {\n    return new Droid();\n  }\n}\n```\n\nNote that when manually creating a dependency Lightsaber doesn't perform field and method injection into the returned\ninstance. But you can do that via [manual injection](#manual-injection) or by creating a dependency with an\n[injectable constructor](#injectable-constructors).\n\n##### Components\n\nComponents now deprecated and will be removed in further versions. Use [contracts](#contracts)\ninstead)\n\n##### Nested modules \n\nModules can import other modules. So if you have a reusable module with some common dependencies you\ncan import it to another module:\n\n```java\n@Module\npublic class CommonDroidModule {\n  @Provide\n  public Battery provideBattery() {\n    return new Battery();\n  }\n}\n\n@Module\npublic class DroidModule {\n  @Import\n  public CommonDroidModule importCommonDroidModule() {\n    return new CommonDroidModule();\n  }\n}\n```  \n\n##### Inversion of import\n\nSometimes you may want to specify that a module should be imported by another modules without\nmodifying them. It can be achieved by applying the `@ImportedBy` annotation to the module that needs to be imported:\n\n```java\n\n@Module\npublic class RobotModule {\n    /* ... */\n}\n\n@Module\n@ImportedBy(RobotModule.class)\npublic class DroidModule {\n    /* ... */\n}\n```\n\n\n#### Injectable constructors\n\nA class may have one and only one injectable constructor. This constructor must be annotated\nwith `@Inject` and can have any number of arguments. When instantiating a class with an injectable\nconstructor via an injector the injector must be able to provide instances for every argument of the\nconstructor.\n\nClasses with injectable constructors should be bound to a module and thus to a contract\nconfiguration that provides the module. This binding can be defined by annotating the class\nwith `@ProvidedBy` annotation and specifying module classes in its default parameter.\n\n```java\n@ProvidedBy(DroidModule.class)\npublic class Droid {\n  @Inject\n  public Droid(Battery battery) {\n  }\n}\n```\n\nWhen providing a dependency using an injectable constructor Lightsaber will perform field and method injection into\nthe provided instance.\n\n#### `@ProvidedAs` annotation\n\nThe `@ProvidedAs` annotation can be used to bind an interface to an implementation when you don't want to define a\nprovider method in a module. Let's assume you have a `Droid` interface and its `ElectricalDroid` implementation and\nyou want to provide an `ElectricalDroid` instance as a `Droid` dependency.\n\n```java\npublic interface Droid {\n}\n\npublic class ElectricalDroid implements Droid {\n  private Battery battery;\n\n  @Inject\n  public ElectricalDroid(Battery battery) {\n    this.battery = battery;\n  }\n\n  /* ... */\n}\n```\n\nYou can achieve that by adding a provider method to a module:\n\n```java\n@Module\npublic class DroidModule {\n  @Provide\n  public Droid provideDroid(final ElectricalDroid droid) {\n    return droid;\n  }\n}\n```\n\nBut this approach would require the `DroidModule` to be aware of the `ElectricalDroid` implementation, which isn't\nalways the case. Another way to do that is to annotate `ElectricalDroid` with the `@ProvidedAs` annotation:\n\n```java\n@ProvidedAs(Droid.class)\npublic class ElectricalDroid implements Droid {\n  /* ... */\n}\n```\n\n### Manual injection\n\nManual injection is a way to create an instance of a provided type or to perform field and method injection into an\nexisting object. An instance can be obtained by calling the `getInstance()` method of the `Injector`:\n\n```\nDroid droid = injector.getInstance(Droid.class);\n```\n\nIf you need a factory that provides instances of a given type you can get a `Provider` object from the `Injector`.\nThen you'll be able to get an instance from the `Provider` by calling its `get()` method: \n\n```\nProvider\u003cDroid\u003e droidProvider = injector.getProvider(Droid.class);\nDroid droid = droidProvider.get();\n```\n\nWhen creating an instance of a dependency manually Lightsaber performs field and method injection\nfor this instance. But sometimes you already have an instance and want to inject dependencies into\nit. You can do that by calling the\n`injectMembers()` method of the `Injector` passing the instance to it.\n\n```java\npublic class DroidController {\n  @Inject\n  private Droid droid;\n\n  public void initialize(Injector injector) {\n    injector.injectMembers(this);\n  }\n}\n```\n\nConsider the following example. We have a `Droid` interface and its implementation and we want to provide `Droid` as a\ndependency.\n\n```java\npublic interface Droid {\n  /* ... */\n}\n\npublic class ElectricalDroid implements Droid {\n  @Inject\n  private Battery battery;\n\n  /* ... */\n}\n```\n\nIf we just create an `ElectricalDroid` instance and return it from a provider method the `battery` field will not be\ninitialized because Lightsaber doesn't perform injection into instances it doesn't manage. But we can fix that by\nmanually injecting dependencies into the instance using the `injectMembers()` method.\n\n```java\n@Module\npublic class DroidModule {\n  @Provide\n  public Droid provideDroid(Injector injector) {\n    Droid droid = new ElectircalDroid();\n    injector.injectMemebers(droid);\n    return droid;\n  }\n}\n```\n\nWhile this is a working example it can be refactored to using constructor injection. In this case manual injection\nbecomes unnecessary.\n\n```java\npublic class ElectricalDroid implements Droid {\n  private Battery battery;\n\n  @Inject\n  public ElectricalDroid(Battery battery) {\n    this.battery = battery;\n  }\n\n  /* ... */\n}\n```\n\n```java\n@Module\npublic class DroidModule {\n  @Provide\n  public Droid provideDroid(ElectricalDroid droid) {\n    return droid;\n  }\n}\n```\n\n### Singleton injection\n\nBy default Lightsaber creates a new instance every time a dependency is requested. This behavior can be changed so that\nLightsaber will return a single instance of the dependency for a given injector. All you need to do is to apply the\n`@Singleton` annotation to a class with an injectable constructor or to a provider method.\n\n```java\n@Singleton\npublic class ElectricalDroid implements Droid {\n  /* ... */\n}\n```\n\n```java\n@Module\npublic class DroidModule {\n  @Provide\n  @Singleton\n  public Droid provideDroid(ElectricalDroid droid) {\n    return droid;\n  }\n}\n```\n\nIn the example above you can annotate just a class or just a provider method or both the class and the provider method\nwith the `@Singleton` annotation and behavior will be very similar but not exactly the same.\n\nIf the `ElectricalDroid` is a singleton then one and only one instance of this class will be created per an injector\ninstance. And even if the `provideDroid()` method is not annotated with `@Singleton` it will return the same instance\nevery time it's called because it returns a singleton instance of `ElectricalDroid`.\n\nOn the other hand, if the `ElectricalDroid` class isn't a singleton the `provideDroid()` method annotated with\n`@Singleton` will return a cached instance of `ElectricalDroid` so the instance will always be the same. But if\n`ElectricalDroid` is injected somewhere else a new instance of this class will be created.\n\n### Eager injection\n\nWhen using singleton injection a singleton instance is created lazily when it's accessed for the first time. If you need\nthe instance to be created eagerly you can use the `@Eager` annotation with the `@Singleton` annotation. Eager\ndependencies are instantiated during creation of an `Injector` or a contract.\n\n```java\n@Eager\n@Singleton\npublic class EagerDroid implements Droid {\n  /* ... */\n}\n```\n\n### Lazy injection\n\nInstead of creating a dependency instance at injection time its instantiation can be deferred until the object is really\nneeded. For this purpose Lightsaber has a generic `Lazy` interface that can be injected instead of the dependency.\n\n```java\npublic class Droid {\n  @Inject\n  private Lazy\u003cBattery\u003e battery;\n\n  public void charge() {\n    battery.get().charge();\n  }\n}\n```\n\nIn this example a `Battery` instance will be created only when `battery.get()` is called.\n\n### Provider injection\n\nProvider injection is somewhat similar to lazy injection with one major difference: when `Provider.get()` is called\nmultiple times you can receive either the same instance of a dependency or a different instance on each invocation of\nthe `get()` method. Provider injection is useful when you need to pass some arguments to a constructor of an object\nwhile other arguments should be provider by an injector.\n\n```java\npublic class Droid {\n  public Droid(Battery battery, Adapter adapter) {\n    /* ... */\n  }\n}\n```\n\n```java\npublic class DroidFactory {\n  @Inject\n  private Provider\u003cBattery\u003e batteryProvider;\n\n  public Droid createDroidWithAdapter(Adapter adapter) {\n    return new Droid(batteryProvider.get(), adapter);\n  }\n}\n```\n\n### Qualified injection\n\nSometimes you may want to provide different implementations of a single dependency type. You can do that by applying a\nqualifier annotation to a class with an injectable constructor or to a provider method. Then you need to apply the same\nqualifier annotation to the provided dependency at the injection point. A dependency may have either no qualifiers or a\nsingle one.\n\nIn the next example we will create a module that provides two different instances of the `Droid` class. To make\nLightsaber distinguish between these dependencies we will annotate them with the built-in `@Named` qualifier.\n\n```java\n@Module\npublic class DroidModule {\n  @Provide\n  @Singleton\n  @Named(\"R2-D2\")\n  public Droid provideR2D2() {\n    return new Droid(\"R2-D2\");\n  }\n\n  @Provide\n  @Singleton\n  @Named(\"C-3PO\")\n  public Droid provideC3PO() {\n    return new Droid(\"C-3PO\");\n  }\n\n  @Provide\n  @Singleton\n  public Droid provideUnknownDroid() {\n    return new Droid(\"Unknown\");\n  }\n}\n```\n\n```java\npublic class DroidParty {\n  @Inject\n  @Named(\"R2-D2\")\n  private Droid r2d2;\n\n  @Inject\n  @Named(\"C-3PO\")\n  private Droid c3po;\n\n  @Inject\n  private Droid unknownDroid;\n}\n```\n\n#### Custom qualifiers\n\nBesides using the `@Named` qualifier you can create you own one. To do that you need to create an annotation and\nannotate it with the `@Qualifier` annotation.\n\n```java\npublic enum DroidType { R2D2, C3PO }\n\n@Qualifier\n@Retention(RetentionPolicy.RUNTIME)\n@Target({\n    ElementType.TYPE,\n    ElementType.FIELD,\n    ElementType.METHOD,\n    ElementType.PARAMETER\n})\npublic @interface Model {\n  DroidType value();\n}\n```\n\n```java\n@Module\npublic class DroidModule {\n  @Provide\n  @Singleton\n  @Model(DroidType.R2D2)\n  public Droid provideR2D2() {\n    return new Droid(\"R2-D2\");\n  }\n\n  @Provide\n  @Singleton\n  @Model(DroidType.C3PO)\n  public Droid provideC3PO() {\n    return new Droid(\"C-3PO\");\n  }\n}\n```\n\n```java\npublic class DroidParty {\n  @Inject\n  @Model(DroidType.R2D2)\n  private Droid r2d2;\n\n  @Inject\n  @Model(DroidType.C3PO)\n  private Droid c3po;\n}\n```\n\nCustom qualifiers are allowed to have any number of properties of any type. When resolving dependencies Lightsaber\ncompares qualifiers by their types and equality of all their properties.\n\n### Generic injection\n\nWith Lightsaber you can inject dependencies of generic types. The generic dependency has to be a parameterized type\nand its type parameters cannot contain wildcards and type variables.\n\nFor example, these types you can use for injection:\n\n- `List\u003cString\u003e`\n- `Map\u003cString, Collection\u003cString\u003e\u003e`\n- `Collection\u003cint[]\u003e`\n\nAnd these types you cannot use:\n\n- `List\u003c? extends CharSequence\u003e`\n- `Map\u003cString, T\u003e`\n\n### Factories (assisted injection)\n\nIn some cases you may want to instantiate an object passing some arguments to its constructor from an injector and\nprovide some other arguments manually at the instantiation site.\n\nLet's define a `Droid` class that has a constructor with two parameters: a battery and a model:\n\n```java\npublic class Droid {\n  private final Battery battery;\n  private final String model;\n  \n  @Factory.Inject\n  public Droid(Battery battery, @Factory.Parameter String model) {\n    this.battery = battery;\n    this.model = model;\n  }\n  \n  /* ... */\n}\n```\n\n`Droid`'s constructor is annotated with `@Factory.Inject` annotation. This annotation means that\nthis constructor can be used for injections but some of its arguments aren't provided by injector.\nNow let's define a module that will be used for providing a `Battery` for the `Droid`:\n\n```java\n@Module\npublic class DroidModule {\n  @Provide\n  public Battery provideBattery() {\n    return new Battery();\n  }\n}\n```\n\nAs you can see no `String` dependency is provided by the module. In order to create a `Droid` we have to provide a model\nname indirectly at the instantiation site. Lightsaber offers a way to achieve that by supporting factories that can\naccept any arguments and pass them to injectable constructors. \n\n```java\n@Factory\n@ProvidedBy(DroidModule.class)\npublic interface DroidFactory {\n  Droid assembleDroid(String model);\n}\n```\n\nThe factory must be an interface annotated with `@Factory` annotation and may contain any number of\nfactory methods. The factory method may contain any number of parameters with unique types. If you\nneed the factory method to contain multiple parameters of the same type they have to be annotated\nwith different qualifiers like `@Named(\"parameterName\")`. Lightsaber matches factory method's\nparameters with constructor's parameters annotated with `@Factory.Parameter` by a type and a\nqualifier. The injector that provides a factory must be able to provide dependencies for all\nconstructor's parameters that aren't annotated with `@Factory.Parameter`.\n\nAfter the factory is defined as shown above it can be injected or retrieved manually from an\ninjector as any other dependency:\n\n```java\npublic class DroidParty {\n  @Inject\n  public DroidParty(DroidFactory factory) {\n    Droid r2d2 = factory.assembleDroid(\"R2-D2\");\n    Droid c3po = factory.assembleDroid(\"C-3PO\");\n  }\n}\n```\n\nThe dependency type is resolved from the return type of the factory method by default. You can change this behavior by annotating\nthe factory method with `@Factory.Return` annotation with the actual dependency type as an argument:\n\n```java\npublic interface Droid {\n  /* ... */\n}\n\npublic class ElectricalDroid {\n  private final Battery battery;\n  private final String model;\n  \n  @Factory.Inject\n  public Droid(Battery battery, @Factory.Parameter String model) {\n    this.battery = battery;\n    this.model = model;\n  }\n  \n  /* ... */\n}\n\n@Factory\n@ProvidedBy(DroidModule.class)\npublic interface DroidFactory {\n  @Factory.Return(ElectricalDroid.class)\n  Droid assembleDroid(String model);\n}\n```\n\n### Provider interceptors\n\nWhen writing tests you may need to substitute a real dependency with a mock. To be able to do that you can register a `ProviderInterceptor` when\ncreating a `Lightsaber` instance and replace a provider with the one that returns mocks:\n\n```java\nLightsaber lightsaber = new Lightsaber.Builder()\n    .addProviderInterceptor(\n        new ProviderInterceptor() {\n          @Override\n          public Provider\u003c?\u003e intercept(ProviderInterceptor.Chain chain, Key\u003c?\u003e key) {\n            if (key.getType() == Battery.class) {\n              return new Provider\u003cObject\u003e() {\n                @Override\n                public Object get() {\n                  return new TestBattery();\n                }\n              };\n            } else {\n              return chain.proceed(key);\n            }\n          }\n        }\n    )\n    .build();\n``` \n\n### Testing\n\nTo simplify unit testing and dependency substitution you can add a special testing module to your project's configuration:\n\n```groovy\ndependencies {\n  testImplementation 'com.joom.lightsaber:lightsaber-test:1.0.0-alpha14'\n}\n```\n\nThis module allows you to build a `ProviderInterceptor` using a convenient builder API. Moreover, it supports creation of annotation proxies at\nruntime, so you'll be able to deal with qualified dependencies easily.\n\n```java\n// Create a provider of Battery instances.\nProvider\u003cBattery\u003e provider = new Provider\u003cBattery\u003e() {\n  @Override\n  public Battery get() {\n    return new TestBattery();\n  }\n};\n\n// Create a proxy for @Named(\"primary\") annotation.\nNamed annotation = new AnnotationBuilder\u003cNamed\u003e(Named.class)\n    .addMember(\"value\", \"primary\")\n    .build();\n\n// Create a provider interceptor that replaces the primary battery with the test one.\nProviderInterceptor interceptor = new ProviderInterceptorBuilder()\n    .addProviderForClass(Battery.class, annotation, provider)\n    .build();\n\n// Create a Lightsaber instance for unit testing. \nLightsaber lightsaber = new Lightsaber.Builder()\n    .addProviderInterceptor(interceptor)\n    .build();\n``` \n\nLicense\n-------\n\n    Copyright 2020 SIA Joom\n\n    Licensed under the Apache License, Version 2.0 (the \"License\");\n    you may not use this file except in compliance with the License.\n    You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoomcode%2Flightsaber","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjoomcode%2Flightsaber","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoomcode%2Flightsaber/lists"}