Skip to content

Java JSR 330 dependency injection library

License

Notifications You must be signed in to change notification settings

SuppieRK/inject

Repository files navigation

Inject

The work on this software project is in no way associated with my employer nor with the role I'm having at my employer.

I maintain this project alone and as much or as little as my spare time permits using my personal equipment.

Small dependency injection library for Java supporting reflection-based objects creation (aka a factory pattern) using slightly extended JSR 330 specification provided by Jakarta Inject library.

The main goal of this library is to provide the most obvious path to register and reuse dependencies in your code, which was inspired by other libraries such as:

  • Feather - with some features absent here, namely injection into the current class for testing.
  • Dagger 2 - the concept of @Provides is useful, code generation not so much.
  • Guice - without the bloat of additional annotations you might never use or support for Jakarta's servlet,persistence.

In addition to JSR 330 annotations, this library adds its own @Provides annotation to mark methods which produce dependencies for other classes - something that is missing from the specification to let users denote which specific methods outputs should be exposed to other classes.

  • Maven
<dependency>
    <groupId>io.github.suppierk</groupId>
    <artifactId>inject</artifactId>
    <version>1.1.0</version>
</dependency>
  • Gradle (works for both Groovy and Kotlin)
implementation("io.github.suppierk:inject:1.1.0")

SonarCloud

Hello, World!

import jakarta.inject.Inject;
import io.github.suppierk.inject.Provides;
import io.github.suppierk.inject.Injector;

public class HelloWorld {
    static class Provider {
        @Provides
        String helloWorld() {
            return "Hello, World!";
        }
    }

    static class Consumer implements Runnable {
        private final String helloWorld;

        @Inject
        public Consumer(String helloWorld) {
            this.helloWorld = helloWorld;
        }

        @Override
        public void run() {
            System.out.println(helloWorld);
        }
    }

    public static void main(String[] args) {
        final Injector injector = Injector.injector()
                .add(Provider.class, Consumer.class)
                .build();

        injector.get(Consumer.class).run();
    }
}

More examples

  • Visit our Wiki for more in-depth look at the features.
  • Take a look at the complete stack proposal in JIQS repository.