SlideShare a Scribd company logo
DEPENDENCY INJECTION
IN SCALA
... ESPECIALLY WITH PLAY!
By /Michal Bigos @teliatko
AGENDA
1. Introduction
2. Evaluation criteria
3. Covered approaches/frameworks
Spring
Spring-Scala
CDI
Guice
SubCut
Cake
4. Recommendations
INTRODUCTION
CATEGORIZATION OF APPROACHES
Pure Scala approaches: Subcut, Cake
Mixed Java/Scala approaches: Spring-Scala, Guice
Pure Java aproaches: Spring, CDI
INTRODUCTION
WHY JAVA DI FRAMEWORKS AT ALL
Reason 1: Important for existing Java-based projects, when
you need to mix Java and Scala
Reason 2: Mature, proven solutions
EVALUATION CRITERIA
1. As much as possible idiomatic approach
minimal usage of: vars, annotations, special
configuration files
ideal case pure Scala
2. Simple testing
Integration testing
Unit testing too
3. Good fit with Play!
4. No steep learning curve
EVALUATION CRITERIA
Symbols used in evaluation
(+) pros
(-) cons
(±) it depends
EXAMPLE APPLICATION
SPRING
1. Relies heavily on annotations (-)
2. External configuration file is needed (-)
3. Differences are minimal in relation to Java (±)
4. Immutability possible via constructor injection (+)
5. Setter injection requires additional work in Scala (±)
6. Popular well-designed Java framework (+)
7. More than just DI (±)
8. Various testing possibilities (±)
SPRING SPECIALS
SETTER INJECTION
or
@org.springframework.stereotype.Controller
class Translate extends Controller {
@BeanProperty
@(Autowired @beanSetter)
var translator: Translator = _
...
}
@org.springframework.stereotype.Controller
class Translate extends Controller {
private var translator: Translator = _
@Autowired
def setTranslator(translator: Translator): Unit =
this.translator = translator
...
}
SPRING-SCALA
1. No annotations (+)
2. Wiring in code, no external configuration file (+)
3. Work in progress (-)
4. Immutability via contructor injection (+)
5. Spring under the hood (+)
6. Provides DSL to use Spring templates (±)
7. Various testing possibilities (±)
SPRING-SCALA SPECIALS
TEMPLATES
Improvements: functions, Options, manifests
ConnectionFactory connectionFactory = ...
JmsTemplate template = new JmsTemplate(connectionFactory);
template.send("queue", new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("Hello World");
}
});
val connectionFactory : ConnectionFactory = ...
val template = new JmsTemplate(connectionFactory)
template.send("queue") {
session: Session => session.createTextMessage("Hello World")
}
SPRING-SCALA SPECIALS
XML CONFIGURATION
class Person(val firstName: String, val lastName: String) { ... }
<beans>
<bean id="firstName" class="java.lang.String">
<constructor-arg value="John"/>
</bean>
<bean id="lastName" class="java.lang.String">
<constructor-arg value="Doe"/>
</bean>
</beans>
class PersonConfiguration extends FunctionalConfiguration {
importXml("classpath:/names.xml")
val john = bean() {
new Person(getBean("firstName"), getBean("lastName"))
}
}
SPRING-SCALA SPECIALS
CONFIGURATION COMPOSITION
You can use also traits for composition
abstract class PersonConfiguration extends FunctionalConfiguration {
val firstName: String
val lastName: String
bean() {
new Person(firstName, lastName)
}
}
class JohnDoeConfiguration extends PersonConfiguration {
val firstName = singleton() { "John" }
val lastName = singleton() { "Doe" }
}
SPRING-SCALA SPECIALS
PROFILES, INIT AND DESTROY
class DataSourceConfiguration extends FunctionalConfiguration {
profile("dev") {
bean("dataSource") {
new BasicDataSource()
} init {
// Set up properties
} destroy { _.close() }
}
profile("prod") {
bean("dataSource") {
val dataSource = new OracleDataSource()
// Set up properties
dataSource
}
}
}
CDI
THE ONLY SOLUTION I DIDN'T TRY BECAUSE OF ITS LIMITS
1. Java EE Standard (JSR-299), part of every JEE6 compiliant
container (±)
2. Relies heavily on annotations (-)
3. Only Singleton and Dependent scoped beans are injected
as direct dependecies (-)
4. Proxy and ThreadLocal magic behind, doesn't work well
with actors (-)
5. Mulitple implementations (±)
6. Various testing possibilities (±)
CDI
LIMITS
Various scopes: singleton, prototype (dependent), session,
request, application
Only singleton and dependent are injected directly
Other scopes use proxies and thread locals
Restriction on proxied classes:
1. Default constructor => no immutablity
2. No final classes and methods => Scala uses some in
beckground implicitly
GOOGLE GUICE
1. Few annotations needed (±)
2. Only DI nothing else, leaner, easier (+)
3. Wiring in code, no external configuration file (+)
4. Immutability via contructor injection (+)
5. Scala DSL for bindings (+)
6. Easy testing (+)
GOOGLE GUICE SPECIALS
PLAIN VANILLA GUICE
Scala DSLs remove unnecessary classOf calls
SBT dependencies
class TranslationModule extends AbstractModule {
def configure() {
bind( classOf[Translator] ).to( classOf[FrenchTranslator] )
}
}
// Two options
"com.tzavellas" % "sse-guice" % "0.7.1"
"net.codingwell" %% "scala-guice" % "3.0.2"
GOOGLE GUICE SPECIALS
INJECTION AND TESTING
Anytime you can inject members using any arbitrary module.
Relevant for setter injection.
It is possible to override production module with another
module in tests. Use ` instead of '
val runner = ...
injector.injectMembers(runner)
val m = Modules 'override' new ProductionModule 'with' new TestModule
val injector = Guice createInjector m
SUBCUT
1. No annotations (+)
2. Wiring in code, no external configuration file (+)
3. Pure Scala library (+)
4. Intrusive code (-)
5. Actually service locator pattern and not DI (-)
6. Limited testing (-)
SUBCUT
BINDING OPTIONS
Example directly from SubCut website
object SomeConfigurationModule extends NewBindingModule (module => {
import module._ // optional but convenient - allows use of bind inst
ead of module.bind
bind [X] toSingle Y
bind [Z] toProvider { codeToGetInstanceOfZ() }
bind [A] toProvider { implicit module => new AnotherInjectedClass(par
am1, param2) } // module singleton
bind [B] to newInstanceOf [Fred] // create a new instance of Fred
every time - Fred require injection
bind [C] to moduleInstanceOf [Jane] // create a module scoped singlet
on Jane that will be used
bind [Int] idBy PoolSize to 3 // bind an Int identified by Pool
Size to constant 3
bind [String] idBy ServerURL to "http://escalatesoft.com"
})
SUBCUT
LESS INTRUSIVE OPTION
Normal definition of component
Using AutoInjectable
Sad news, it needs compiler plugin (macros in next versions)
class SomeServiceOrClass(param1: String, param2: Int)
(implicit val bindingModule: BindingModule)
extends SomeTrait with Injectable {
...
}
class SomeServiceOrClass(param1: String, param2: Int)
extends SomeTrait with AutoInjectable {
...
}
CAKE PATTERN
1. Dependencies are checked in compile time, statically
typed, immutable (+)
2. No library needed, uses only Scala language features (+)
3. Wiring in code, no external configuration file (+)
4. Uses advanced features of Scala, not easy to grasp (-)
5. Easy testing (+)
CAKE PATTERN
EXPLANATION
Definition of module/component
// Module or Component
trait Translation {
// Services it provides
def translator: Translator
// Service interface with multiple implementations
trait Translator {
def translate(what: String): String
}
}
CAKE PATTERN
EXPLANATION
Implementation of component, relies on inharitance
trait FrenchTranslation extends Translation {
// Singleton instance
override val translator = new FrenchTranslator
// Implementation of service
class FrenchTranslator extends Translator {
def translate(what: String): String = {...}
}
}
CAKE PATTERN
EXPLANATION
Expressing dependency and usage, relies on self-type
annotations
trait Translate extends Controller {
this: Translation => // Dependency
def greet(name: String) = Action {
// Usage of service
Ok(views.html.greet(translator.translate(s"Hello $name!")))
}
}
CAKE PATTERN
EXPLANATION
Binding, relies on mixins of traits
object Translate extends Translate with FrenchTranslation
RECOMMENDATIONS
WHEN TO USE (JAVA FRAMEWORKS)
Spring (definitely w/ Spring-Scala)
1. When you need more than DI
2. When you need to intergate with Java code
3. When you know Spring well
CDI
1. Only in JEE compiliant container, when your code depends
on container services
Guice
1. When you want to do only DI and do it well
2. When you need to integrate with Java code
RECOMMENDATIONS
WHEN TO USE (SCALA DI)
SubCut
1. When you want to be hipster and rant with a new library
2. When you want pure Scala solution
Cake
1. Wnen you need additional type safety
2. When you want pure Scala solution
3. When you want very cohesive components/modules
RECOMMENDATIONS
USAGE EXAMPLES
Java/Scala mixed project => Spring or Guice
Scala standalone project => Guice or Cake
Play! project => Guice or Cake
Domain or algorithm => Cake
RECOMMENDATIONS
VERY SUBJECTIVE RANKING
Category Spring CDI Guice SubCut Cake
Idiomatic ** * ** *** ***
Simple testing *** * *** * ***
Good fit with Play! *** * *** ** ***
No steep learning curve ** ** *** *** *
Java integration *** *** *** n/a n/a
THANKS FOR YOUR ATTENTION

More Related Content

What's hot

Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
Christoffer Noring
 
Demystifying Oak Search
Demystifying Oak SearchDemystifying Oak Search
Demystifying Oak Search
Justin Edelson
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2
DreamLab
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
Christoffer Noring
 
Angular 2 introduction
Angular 2 introductionAngular 2 introduction
Angular 2 introduction
Christoffer Noring
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
BoneyGawande
 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
Visual Engineering
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
Visual Engineering
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
scottw
 
Firebase ng2 zurich
Firebase ng2 zurichFirebase ng2 zurich
Firebase ng2 zurich
Christoffer Noring
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
DreamLab
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
Christoffer Noring
 
Angular 2.0 - What to expect
Angular 2.0 - What to expectAngular 2.0 - What to expect
Angular 2.0 - What to expect
Allan Marques Baptista
 
Angular 1 + es6
Angular 1 + es6Angular 1 + es6
Angular 1 + es6
장현 한
 
G pars
G parsG pars
Workshop 17: EmberJS parte II
Workshop 17: EmberJS parte IIWorkshop 17: EmberJS parte II
Workshop 17: EmberJS parte II
Visual Engineering
 
AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.
Yan Yankowski
 
Workshop 3: JavaScript build tools
Workshop 3: JavaScript build toolsWorkshop 3: JavaScript build tools
Workshop 3: JavaScript build tools
Visual Engineering
 

What's hot (20)

Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Demystifying Oak Search
Demystifying Oak SearchDemystifying Oak Search
Demystifying Oak Search
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
 
Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
 
Angular 2 introduction
Angular 2 introductionAngular 2 introduction
Angular 2 introduction
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
 
Firebase ng2 zurich
Firebase ng2 zurichFirebase ng2 zurich
Firebase ng2 zurich
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Angular 2.0 - What to expect
Angular 2.0 - What to expectAngular 2.0 - What to expect
Angular 2.0 - What to expect
 
Angular 1 + es6
Angular 1 + es6Angular 1 + es6
Angular 1 + es6
 
G pars
G parsG pars
G pars
 
Workshop 17: EmberJS parte II
Workshop 17: EmberJS parte IIWorkshop 17: EmberJS parte II
Workshop 17: EmberJS parte II
 
AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.
 
Workshop 3: JavaScript build tools
Workshop 3: JavaScript build toolsWorkshop 3: JavaScript build tools
Workshop 3: JavaScript build tools
 

Viewers also liked

DUMP-2015: «Распределенная обработка миллионов документов на Scala и Akka» Ст...
DUMP-2015: «Распределенная обработка миллионов документов на Scala и Akka» Ст...DUMP-2015: «Распределенная обработка миллионов документов на Scala и Akka» Ст...
DUMP-2015: «Распределенная обработка миллионов документов на Scala и Akka» Ст...
it-people
 
[Start] Playing
[Start] Playing[Start] Playing
[Start] Playing
佑介 九岡
 
Playing with Scala
Playing with ScalaPlaying with Scala
Playing with Scala
Tamer Abdul-Radi
 
Play Template Engine Based On Scala
Play Template Engine Based On ScalaPlay Template Engine Based On Scala
Play Template Engine Based On Scala
Knoldus Inc.
 
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
Matt Raible
 
Designing Reactive Systems with Akka
Designing Reactive Systems with AkkaDesigning Reactive Systems with Akka
Designing Reactive Systems with Akka
Thomas Lockney
 
Your First Scala Web Application using Play 2.1
Your First Scala Web Application using Play 2.1Your First Scala Web Application using Play 2.1
Your First Scala Web Application using Play 2.1
Matthew Barlocker
 
Play framework And Google Cloud Platform GCP.
Play framework And Google Cloud Platform GCP.Play framework And Google Cloud Platform GCP.
Play framework And Google Cloud Platform GCP.
Eng Chrispinus Onyancha
 
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVMVoxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Manuel Bernhardt
 
Введение в Akka
Введение в AkkaВведение в Akka
Введение в AkkaZheka Kozlov
 
Reactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysReactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDays
Manuel Bernhardt
 
Akka-http
Akka-httpAkka-http
Akka-http
Iosif Itkin
 
Lagom in Practice
Lagom in PracticeLagom in Practice
Lagom in Practice
JWORKS powered by Ordina
 
Akka http 2
Akka http 2Akka http 2
Akka http 2
Jean Detoeuf
 
Язык программирования Scala / Владимир Успенский (TCS Bank)
Язык программирования Scala / Владимир Успенский (TCS Bank)Язык программирования Scala / Владимир Успенский (TCS Bank)
Язык программирования Scala / Владимир Успенский (TCS Bank)Ontico
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps
Yevgeniy Brikman
 
Akka http
Akka httpAkka http
Akka http
Knoldus Inc.
 
Practical Akka HTTP - introduction
Practical Akka HTTP - introductionPractical Akka HTTP - introduction
Practical Akka HTTP - introduction
Łukasz Sowa
 
Agile for Embedded & System Software Development : Presented by Priyank KS
Agile for Embedded & System Software Development : Presented by Priyank KS Agile for Embedded & System Software Development : Presented by Priyank KS
Agile for Embedded & System Software Development : Presented by Priyank KS
oGuild .
 
3.7 heap sort
3.7 heap sort3.7 heap sort
3.7 heap sort
Krish_ver2
 

Viewers also liked (20)

DUMP-2015: «Распределенная обработка миллионов документов на Scala и Akka» Ст...
DUMP-2015: «Распределенная обработка миллионов документов на Scala и Akka» Ст...DUMP-2015: «Распределенная обработка миллионов документов на Scala и Akka» Ст...
DUMP-2015: «Распределенная обработка миллионов документов на Scala и Akka» Ст...
 
[Start] Playing
[Start] Playing[Start] Playing
[Start] Playing
 
Playing with Scala
Playing with ScalaPlaying with Scala
Playing with Scala
 
Play Template Engine Based On Scala
Play Template Engine Based On ScalaPlay Template Engine Based On Scala
Play Template Engine Based On Scala
 
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
 
Designing Reactive Systems with Akka
Designing Reactive Systems with AkkaDesigning Reactive Systems with Akka
Designing Reactive Systems with Akka
 
Your First Scala Web Application using Play 2.1
Your First Scala Web Application using Play 2.1Your First Scala Web Application using Play 2.1
Your First Scala Web Application using Play 2.1
 
Play framework And Google Cloud Platform GCP.
Play framework And Google Cloud Platform GCP.Play framework And Google Cloud Platform GCP.
Play framework And Google Cloud Platform GCP.
 
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVMVoxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
 
Введение в Akka
Введение в AkkaВведение в Akka
Введение в Akka
 
Reactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysReactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDays
 
Akka-http
Akka-httpAkka-http
Akka-http
 
Lagom in Practice
Lagom in PracticeLagom in Practice
Lagom in Practice
 
Akka http 2
Akka http 2Akka http 2
Akka http 2
 
Язык программирования Scala / Владимир Успенский (TCS Bank)
Язык программирования Scala / Владимир Успенский (TCS Bank)Язык программирования Scala / Владимир Успенский (TCS Bank)
Язык программирования Scala / Владимир Успенский (TCS Bank)
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps
 
Akka http
Akka httpAkka http
Akka http
 
Practical Akka HTTP - introduction
Practical Akka HTTP - introductionPractical Akka HTTP - introduction
Practical Akka HTTP - introduction
 
Agile for Embedded & System Software Development : Presented by Priyank KS
Agile for Embedded & System Software Development : Presented by Priyank KS Agile for Embedded & System Software Development : Presented by Priyank KS
Agile for Embedded & System Software Development : Presented by Priyank KS
 
3.7 heap sort
3.7 heap sort3.7 heap sort
3.7 heap sort
 

Similar to Dependency injection in scala

SCR Annotations for Fun and Profit
SCR Annotations for Fun and ProfitSCR Annotations for Fun and Profit
SCR Annotations for Fun and Profit
Mike Pfaff
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
JAX London
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
Schalk Cronjé
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing Support
Sam Brannen
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Apache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolboxApache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolbox
Antoine Sabot-Durand
 
Apache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI ToolboxApache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI Toolbox
Virtual JBoss User Group
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
Naga Muruga
 
Scala and Spring
Scala and SpringScala and Spring
Scala and Spring
Eberhard Wolff
 
SBT Crash Course
SBT Crash CourseSBT Crash Course
SBT Crash Course
Michal Bigos
 
Idiomatic gradle plugin writing
Idiomatic gradle plugin writingIdiomatic gradle plugin writing
Idiomatic gradle plugin writing
Schalk Cronjé
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
Shivam Singhal
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
Schalk Cronjé
 
Improving your Gradle builds
Improving your Gradle buildsImproving your Gradle builds
Improving your Gradle builds
Peter Ledbrook
 
Spock
SpockSpock
Modular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJSModular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJS
Gunnar Hillert
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
Schalk Cronjé
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
Naga Muruga
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
Appster1
 
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfdokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
Appster1
 

Similar to Dependency injection in scala (20)

SCR Annotations for Fun and Profit
SCR Annotations for Fun and ProfitSCR Annotations for Fun and Profit
SCR Annotations for Fun and Profit
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing Support
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Apache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolboxApache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolbox
 
Apache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI ToolboxApache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI Toolbox
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
Scala and Spring
Scala and SpringScala and Spring
Scala and Spring
 
SBT Crash Course
SBT Crash CourseSBT Crash Course
SBT Crash Course
 
Idiomatic gradle plugin writing
Idiomatic gradle plugin writingIdiomatic gradle plugin writing
Idiomatic gradle plugin writing
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
Improving your Gradle builds
Improving your Gradle buildsImproving your Gradle builds
Improving your Gradle builds
 
Spock
SpockSpock
Spock
 
Modular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJSModular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJS
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
 
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfdokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
 

Recently uploaded

Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 

Recently uploaded (20)

Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 

Dependency injection in scala

  • 1. DEPENDENCY INJECTION IN SCALA ... ESPECIALLY WITH PLAY! By /Michal Bigos @teliatko
  • 2. AGENDA 1. Introduction 2. Evaluation criteria 3. Covered approaches/frameworks Spring Spring-Scala CDI Guice SubCut Cake 4. Recommendations
  • 3. INTRODUCTION CATEGORIZATION OF APPROACHES Pure Scala approaches: Subcut, Cake Mixed Java/Scala approaches: Spring-Scala, Guice Pure Java aproaches: Spring, CDI
  • 4. INTRODUCTION WHY JAVA DI FRAMEWORKS AT ALL Reason 1: Important for existing Java-based projects, when you need to mix Java and Scala Reason 2: Mature, proven solutions
  • 5. EVALUATION CRITERIA 1. As much as possible idiomatic approach minimal usage of: vars, annotations, special configuration files ideal case pure Scala 2. Simple testing Integration testing Unit testing too 3. Good fit with Play! 4. No steep learning curve
  • 6. EVALUATION CRITERIA Symbols used in evaluation (+) pros (-) cons (±) it depends
  • 8. SPRING 1. Relies heavily on annotations (-) 2. External configuration file is needed (-) 3. Differences are minimal in relation to Java (±) 4. Immutability possible via constructor injection (+) 5. Setter injection requires additional work in Scala (±) 6. Popular well-designed Java framework (+) 7. More than just DI (±) 8. Various testing possibilities (±)
  • 9. SPRING SPECIALS SETTER INJECTION or @org.springframework.stereotype.Controller class Translate extends Controller { @BeanProperty @(Autowired @beanSetter) var translator: Translator = _ ... } @org.springframework.stereotype.Controller class Translate extends Controller { private var translator: Translator = _ @Autowired def setTranslator(translator: Translator): Unit = this.translator = translator ... }
  • 10.
  • 11. SPRING-SCALA 1. No annotations (+) 2. Wiring in code, no external configuration file (+) 3. Work in progress (-) 4. Immutability via contructor injection (+) 5. Spring under the hood (+) 6. Provides DSL to use Spring templates (±) 7. Various testing possibilities (±)
  • 12. SPRING-SCALA SPECIALS TEMPLATES Improvements: functions, Options, manifests ConnectionFactory connectionFactory = ... JmsTemplate template = new JmsTemplate(connectionFactory); template.send("queue", new MessageCreator() { public Message createMessage(Session session) throws JMSException { return session.createTextMessage("Hello World"); } }); val connectionFactory : ConnectionFactory = ... val template = new JmsTemplate(connectionFactory) template.send("queue") { session: Session => session.createTextMessage("Hello World") }
  • 13. SPRING-SCALA SPECIALS XML CONFIGURATION class Person(val firstName: String, val lastName: String) { ... } <beans> <bean id="firstName" class="java.lang.String"> <constructor-arg value="John"/> </bean> <bean id="lastName" class="java.lang.String"> <constructor-arg value="Doe"/> </bean> </beans> class PersonConfiguration extends FunctionalConfiguration { importXml("classpath:/names.xml") val john = bean() { new Person(getBean("firstName"), getBean("lastName")) } }
  • 14. SPRING-SCALA SPECIALS CONFIGURATION COMPOSITION You can use also traits for composition abstract class PersonConfiguration extends FunctionalConfiguration { val firstName: String val lastName: String bean() { new Person(firstName, lastName) } } class JohnDoeConfiguration extends PersonConfiguration { val firstName = singleton() { "John" } val lastName = singleton() { "Doe" } }
  • 15. SPRING-SCALA SPECIALS PROFILES, INIT AND DESTROY class DataSourceConfiguration extends FunctionalConfiguration { profile("dev") { bean("dataSource") { new BasicDataSource() } init { // Set up properties } destroy { _.close() } } profile("prod") { bean("dataSource") { val dataSource = new OracleDataSource() // Set up properties dataSource } } }
  • 16. CDI THE ONLY SOLUTION I DIDN'T TRY BECAUSE OF ITS LIMITS 1. Java EE Standard (JSR-299), part of every JEE6 compiliant container (±) 2. Relies heavily on annotations (-) 3. Only Singleton and Dependent scoped beans are injected as direct dependecies (-) 4. Proxy and ThreadLocal magic behind, doesn't work well with actors (-) 5. Mulitple implementations (±) 6. Various testing possibilities (±)
  • 17. CDI LIMITS Various scopes: singleton, prototype (dependent), session, request, application Only singleton and dependent are injected directly Other scopes use proxies and thread locals Restriction on proxied classes: 1. Default constructor => no immutablity 2. No final classes and methods => Scala uses some in beckground implicitly
  • 18. GOOGLE GUICE 1. Few annotations needed (±) 2. Only DI nothing else, leaner, easier (+) 3. Wiring in code, no external configuration file (+) 4. Immutability via contructor injection (+) 5. Scala DSL for bindings (+) 6. Easy testing (+)
  • 19. GOOGLE GUICE SPECIALS PLAIN VANILLA GUICE Scala DSLs remove unnecessary classOf calls SBT dependencies class TranslationModule extends AbstractModule { def configure() { bind( classOf[Translator] ).to( classOf[FrenchTranslator] ) } } // Two options "com.tzavellas" % "sse-guice" % "0.7.1" "net.codingwell" %% "scala-guice" % "3.0.2"
  • 20. GOOGLE GUICE SPECIALS INJECTION AND TESTING Anytime you can inject members using any arbitrary module. Relevant for setter injection. It is possible to override production module with another module in tests. Use ` instead of ' val runner = ... injector.injectMembers(runner) val m = Modules 'override' new ProductionModule 'with' new TestModule val injector = Guice createInjector m
  • 21. SUBCUT 1. No annotations (+) 2. Wiring in code, no external configuration file (+) 3. Pure Scala library (+) 4. Intrusive code (-) 5. Actually service locator pattern and not DI (-) 6. Limited testing (-)
  • 22. SUBCUT BINDING OPTIONS Example directly from SubCut website object SomeConfigurationModule extends NewBindingModule (module => { import module._ // optional but convenient - allows use of bind inst ead of module.bind bind [X] toSingle Y bind [Z] toProvider { codeToGetInstanceOfZ() } bind [A] toProvider { implicit module => new AnotherInjectedClass(par am1, param2) } // module singleton bind [B] to newInstanceOf [Fred] // create a new instance of Fred every time - Fred require injection bind [C] to moduleInstanceOf [Jane] // create a module scoped singlet on Jane that will be used bind [Int] idBy PoolSize to 3 // bind an Int identified by Pool Size to constant 3 bind [String] idBy ServerURL to "http://escalatesoft.com" })
  • 23. SUBCUT LESS INTRUSIVE OPTION Normal definition of component Using AutoInjectable Sad news, it needs compiler plugin (macros in next versions) class SomeServiceOrClass(param1: String, param2: Int) (implicit val bindingModule: BindingModule) extends SomeTrait with Injectable { ... } class SomeServiceOrClass(param1: String, param2: Int) extends SomeTrait with AutoInjectable { ... }
  • 24. CAKE PATTERN 1. Dependencies are checked in compile time, statically typed, immutable (+) 2. No library needed, uses only Scala language features (+) 3. Wiring in code, no external configuration file (+) 4. Uses advanced features of Scala, not easy to grasp (-) 5. Easy testing (+)
  • 25. CAKE PATTERN EXPLANATION Definition of module/component // Module or Component trait Translation { // Services it provides def translator: Translator // Service interface with multiple implementations trait Translator { def translate(what: String): String } }
  • 26. CAKE PATTERN EXPLANATION Implementation of component, relies on inharitance trait FrenchTranslation extends Translation { // Singleton instance override val translator = new FrenchTranslator // Implementation of service class FrenchTranslator extends Translator { def translate(what: String): String = {...} } }
  • 27. CAKE PATTERN EXPLANATION Expressing dependency and usage, relies on self-type annotations trait Translate extends Controller { this: Translation => // Dependency def greet(name: String) = Action { // Usage of service Ok(views.html.greet(translator.translate(s"Hello $name!"))) } }
  • 28. CAKE PATTERN EXPLANATION Binding, relies on mixins of traits object Translate extends Translate with FrenchTranslation
  • 29. RECOMMENDATIONS WHEN TO USE (JAVA FRAMEWORKS) Spring (definitely w/ Spring-Scala) 1. When you need more than DI 2. When you need to intergate with Java code 3. When you know Spring well CDI 1. Only in JEE compiliant container, when your code depends on container services Guice 1. When you want to do only DI and do it well 2. When you need to integrate with Java code
  • 30. RECOMMENDATIONS WHEN TO USE (SCALA DI) SubCut 1. When you want to be hipster and rant with a new library 2. When you want pure Scala solution Cake 1. Wnen you need additional type safety 2. When you want pure Scala solution 3. When you want very cohesive components/modules
  • 31. RECOMMENDATIONS USAGE EXAMPLES Java/Scala mixed project => Spring or Guice Scala standalone project => Guice or Cake Play! project => Guice or Cake Domain or algorithm => Cake
  • 32. RECOMMENDATIONS VERY SUBJECTIVE RANKING Category Spring CDI Guice SubCut Cake Idiomatic ** * ** *** *** Simple testing *** * *** * *** Good fit with Play! *** * *** ** *** No steep learning curve ** ** *** *** * Java integration *** *** *** n/a n/a
  • 33. THANKS FOR YOUR ATTENTION