SlideShare a Scribd company logo
1 of 33
Download to read offline
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

Demystifying Oak Search
Demystifying Oak SearchDemystifying Oak Search
Demystifying Oak SearchJustin 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 #2DreamLab
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
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 & ReduxVisual 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 SideVisual Engineering
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgetsscottw
 
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
 
Angular 1 + es6
Angular 1 + es6Angular 1 + es6
Angular 1 + es6장현 한
 
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 toolsVisual 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
 
Play Template Engine Based On Scala
Play Template Engine Based On ScalaPlay Template Engine Based On Scala
Play Template Engine Based On ScalaKnoldus 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 2011Matt Raible
 
Designing Reactive Systems with Akka
Designing Reactive Systems with AkkaDesigning Reactive Systems with Akka
Designing Reactive Systems with AkkaThomas 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.1Matthew 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 JVMManuel Bernhardt
 
Введение в Akka
Введение в AkkaВведение в Akka
Введение в AkkaZheka Kozlov
 
Reactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysReactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysManuel Bernhardt
 
Язык программирования 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 appsYevgeniy Brikman
 
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 .
 

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 ProfitMike 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 WolffJAX London
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingSchalk 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 SupportSam Brannen
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2Naga Muruga
 
Idiomatic gradle plugin writing
Idiomatic gradle plugin writingIdiomatic gradle plugin writing
Idiomatic gradle plugin writingSchalk 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, constructorShivam Singhal
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingSchalk Cronjé
 
Improving your Gradle builds
Improving your Gradle buildsImproving your Gradle builds
Improving your Gradle buildsPeter Ledbrook
 
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 AngularJSGunnar Hillert
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingSchalk Cronjé
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga 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).pdfAppster1
 
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.pdfAppster1
 

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

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 

Recently uploaded (20)

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

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