I know that the best way to deal with dependency injection in Scala is using tools that were built specifically for the language, but I working on a project that must integrate some Scala and Java code.
Then, I am using Google Guice, that implements specification JSR-330. Fortunatly, I found no problem during integration of Guice and Scala. I am using constructor injection, because I have to deal with immutability.
My question is, why in Scala we have to use the notation @Inject()
in front of the constructor parameter? Why the ()
paranthesis? It follows an example:
class MyClass @Inject() (val another: AnotherClass) {
// Body of the class
}
The @Inject annotation lets us define an injection point that is injected during bean instantiation. Injection can occur via three different mechanisms. Bean constructor parameter injection: public class Checkout { private final ShoppingCart cart; @Inject.
Introduction to Scala Dependency Injection. Dependency Injection is the software design pattern used to simplify our logic. Dependency Injection separates our implemented methods, and interfaces provide us benefits from debugging our code easily.
@Inject annotates constructors and methods that determine what an object needs to be initialized. There are also a lot of other annotations that determine how Guice works. But simply annotating objects isn't enough; you also have to configure them with Guice bindings.
Annotation Type Inject. @Target(value={METHOD,CONSTRUCTOR,FIELD}) @Retention(value=RUNTIME) @Documented public @interface Inject. Annotates members of your implementation class (constructors, methods and fields) into which the Injector should inject values.
Otherwise, how could you tell if (val another: AnotherClass)
is constructor parameter list or arguments to @Inject
?
It is all about the syntax of annotating a constructor. Scala requires a constructor annotation to have one (and exactly one) parameter list (even if it is empty)
class Bar @Fooable() ( val i : Int) {
}
What would the i
parameter belong to below: The annotation or the Bar
class?
class Bar @Fooable( val i : Int) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With