Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Dependency Injection in Scala

Dependency Injection in Scala

Presented at Czech Scala Enthusiasts meetup in January 2013.

Jakub Janeček

January 29, 2013
Tweet

More Decks by Jakub Janeček

Other Decks in Programming

Transcript

  1. Java DI frameworks with Scala • important for existing Java-based

    projects/platforms • Java-Scala interoperability on JVM-level bears fruits • some issues may arise ◦ we will show some later
  2. Spring • most popular • well-designed • a lot more

    than just an IoC container • a lot of people have experimented with Spring + Scala • SpringSource is working on the Spring Scala project
  3. Spring observations • actual differences between Java and Scala were

    minimal • constructor injection works well with immutability • setter injection requires some additional work
  4. Spring Scala project • developed by SpringSource • targets Spring

    3.2 • work in progres (1.0.0.M1) • wiring beans using functional syntax • functional wrappers for Spring templates ◦ functions instead of anonymous callbacks
  5. Google Guice • focuses only on the DI • leaner,

    easier to get into • less magic • explicit bindings ◦ defined in module classes • just-in-time bindings ◦ automatic discovery
  6. Guice Observations • simplicity • interesting if you don't need

    (or want) Spring • easy to integrate with other frameworks (even the Scala ones)
  7. Contexts and Dependency Injection • the standard (JSR-299) • part

    of Java EE 6 (and every compliant container) • created with lessons from previous DI solutions in mind
  8. Scopes and Contexts • singleton • prototype (aka dependent) •

    session • request • application • ...
  9. Scopes cont. • in CDI, only singleton and dependent are

    injected as direct references ◦ different lifecycles, serialization • DI framework will inject a proxy instead ◦ thread-local magic
  10. Proxies • restrictions on the proxied class ◦ might vary

    between DI frameworks • needs a default constructor • cannot be final or have final methods
  11. Proxy problems • Scala compiler emits final methods ◦ even

    if there are none in the source code • access to a private val from a closure • such class is "unproxyable"
  12. Java DI Frameworks Summary • you can use them if

    you want ◦ Spring is not just DI
  13. Java DI Frameworks Summary • problems may arise if there

    are additional restrictions on classes (setters, proxies, ...) ◦ these can be avoided with some effort
  14. SubCut "Scala Uniquely Bound Classes Under Traits" https://github.com/dickwall/subcut • very

    small and simple DI library • pure and idiomatic Scala • binding DSL • uses implicits to cut down on boilerplate JavaPosse ScalaWags
  15. Pros&Cons • Pros ◦ straightforward and simple ◦ idiomatic •

    Cons ◦ no automatic injection ◦ possible runtime errors (not static as Cake)