A fast and (very) lightweight Dependency Injection Framework for Java
Use InjectorFactory.create
to create an Injector.
Example:
Injector injector = InjectorFactory.create(modules);
Where "modules" is a Module
array or Iterable<Module>
And get the instance of a class by doing this:
Foo foo = injector.getInstance(Foo.class);
Or injecting dependencies to already instantiated objects
Foo foo = new Foo();
injector.injectMembers(foo);
Creating a module is as simple as creating a class that extends Module
and override configure
method
Linker
is like Guice's Binder
The way to configure links is very similar to the way to configure bindings in Guice
import me.yushust.inject.bind.Module;
import me.yushust.inject.bind.Binder;
public class MySimpleModule implements Module {
@Override
public void configure(Binder binder) {
}
}
So, we will make a binding, from Foo to Bar Foo must implement Bar
@Override
public void configure(Binder binder) {
binder.bind(Foo.class).to(Bar.class);
}
We can also make generic links using Token
@Override
public void configure(Binder binder) {
// The {} are important!
binder.bind(new Token<List<String>>() {}).toInstance(new ArrayList<>());
// The links to instance are Singleton by default
}
It is also possible to make links with annotations (called Qualifiers)
@Override
public void configure(Binder binder) {
binder.bind(Foo.class)
.qualified(FooAnnotation.class)
.to(Bar.class);
}
So the injection would look like this:
@Inject @FooAnnotation
private Foo foo;
(FooAnnotation must be annotated with @BindingAnnotation
or @Qualifier
)
Something like this:
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.PARAMETER })
@BindingAnnotation
public @interface FooAnnotation {
}
Syringe does not detect cycle dependencies. So, you should avoid making confusing links.
# Clone the repository
git clone https://github.com/yusshu/syringe
# Move into the folder
cd syringe
# Install syringe using Maven
mvn clean install
<dependency>
<groupId>me.yushust.inject</groupId>
<artifactId>syringe-core</artifactId>
<version>0.2.1</version>
</dependency>