SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

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
 

Tendances (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
 

En vedette

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 .
 

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Dernier

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
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
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Dernier (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

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