Implementation of JSR-330(Dependency Injection standard for Java)
git clone git@github.com:nokok/Draft.git
cd Draft
./gradlew build # Requirements: JDK 11 or above
- Compile-Time verification(Experimental)
- Only depends on
javax.inject
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>
// SampleModule.java
import net.nokok.draft.Module;
@Module
public interface SampleModule {
ServiceImpl bind(Service s);
}
// 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();
}
}
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";
}
}
@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
...
}
}
./gradlew build signFiles publishToMavenLocal