Skip to content
/ Draft Public

Implementation of JSR-330(Dependency Injection standard for Java)

License

Notifications You must be signed in to change notification settings

nokok/Draft

Repository files navigation

Draft

Implementation of JSR-330(Dependency Injection standard for Java)

CircleCI GitHub Maintainability

Build

git clone git@github.com:nokok/Draft.git
cd Draft
./gradlew build # Requirements: JDK 11 or above

Features

  • Compile-Time verification(Experimental)
  • Only depends on javax.inject

Getting Started

1. Configure Gradle/Maven

Gradle

dependencies {
    implementation 'javax.inject:javax.inject:1'
    implementation 'net.nokok.draft:draft:$version'
    annotationProcessor ('net.nokok.draft:draft:$version')
}

Maven

<dependency>
    <groupId>javax.inject</groupId>
    <artifactId>javax.inject</artifactId>
    <version>1</version>
</dependency>
<dependency>
    <groupId>net.nokok.draft</groupId>
    <artifactId>draft</artifactId>
    <version>$version</version>
</dependency>

2. Configure Module

// SampleModule.java
import net.nokok.draft.Module;

@Module
public interface SampleModule {
    ServiceImpl bind(Service s);
}

3. Create injector

// Main.java
import net.nokok.draft.Injector;

public class Main {
    public static void main(String[] args) {
        Injector injector = Injector.fromModule(SampleModule.class);
        injector.getInstance(Service.class); // new ServiceImpl();
    }
}

Documentation(WIP)

e.g.

interface Service {...}
class ServiceImpl implements Service {...}

interface GenericService<T> {...}
class GenericServiceImpl<T> implements GenericService<T> {...}

Configure

@Module
public interface SampleModule {
    // bind Service to ServiceImpl
    ServiceImpl bindService(Service s);

    // bind GenericService<SomeClass> to GenericServiceImpl<SomeClass>
    GenericServiceImpl<SomeClass> bindGenericServiceSomeClass(GenericService<SomeClass> s);

    // bind instance
    @Named("ApplicationTitle")
    default String title() {
        return "App";
    }
}

Override bindings

@Module
public interface Production {
    @Named("DatabaseUrl")
    default String databaseUrl() {
        return "jdbc:mysql://prod-db:3306/db";
    }
}

@Module
public interface Local extends Production {
    @Override
    @Named("DatabaseUrl")
    default String databaseUrl() {
        return "jdbc:mysql://localhost:3306/db";
    }
}

// ...

Injector injector;
if(isProd){
    injector = Injector.fromModule(Production.class);
} else {
    injector = Injector.fromModule(Local.class);
}

/// ...

public class Repository {

    @Inject
    public Repository(@Named("DatabaseUrl") String databaseUrl) {
        // You can switch the databaseUrl dependening on the environment
        ...
    }
}

Publish

./gradlew build signFiles publishToMavenLocal

About

Implementation of JSR-330(Dependency Injection standard for Java)

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published