SlideShare a Scribd company logo
Scala and Spring
            Eberhard Wolff
Architecture and Technology Manager
        adesso AG, Germany
Why Scala and Spring?
•  Scala                  •  Spring
  –  Strongly typed          –  The tools for
     language                   enterprise apps
  –  Elegant                 –  Well established
  –  Functional              –  Lots of know how
     programming             –  Very flexible
  –  Focus on
     Concurrency
  –  Lack of enterprise
     frameworks
Spring‘s Core Elements
•  Dependency Injection
  –  Organize the collaboration of objects
•  Aspect Oriented Programming
  –  Handle cross cutting concerns like security
     or transactions
•  Portable Service Abstraction
  –  Easy, unified APIs for JMS, JDBC, tx …
•  Testing
•  How can they be used with Scala?
Dependency Injection
Dependency Injection
•  Depended objects are injected

•  Advantages:
  –  Better handling of dependencies
  –  Easier testability

  –  Easier configuration
Dependency Injection
•    Dependency Injection is a Pattern
•    i.e. you can implement it in code
•    …and therefore in plain Scala
•    Configuration in a file: more flexibility
     –  No compile / redeploy
     –  Configure values, not just references


•  Spring offers a lot of approaches to DI
Example
   •  DAO depends on a DataSource	
   •  Injected in the constructor
   •  Matches Scala’s immutability approach
class CustomerDAO(dataSource: DataSource) {	
   	
   val jdbcTemplate = new JdbcTemplate(dataSource)	
	
...	
	
}
On Singletons
•  Scala introduces objects as Singletons
•  Example uses Scala classes
•  Spring needs to do the creation so
   Dependency Injection can be done
•  Might consider @Configurable but
   that adds AspectJ Load Time
   Weaving…
•  More flexibility concerning scopes
Spring XML Configuration
<beans ...>	
	
  <jdbc:embedded-database type="HSQL"	
     id="dataSource" />	
	
  <bean id="customerDAO" 	
   class="de.adesso.scalaspring.dao.CustomerDAO">	
    <constructor-arg ref="dataSource" />	
  </bean>	
	
</beans>
Spring XML Configuration
•  Very easy and little difference to Java
•  For optional configuration:
   Use @BeanProperty to generate
   getters and setters
•  Marks property as configurable by
   Spring
•  Might want to create your own
   Conversions to configure Scala types
Spring XML & Scala Collections
   •  Scala has its own collection classes
   •  Cannot be configured with Spring XML
      out of the box
   •  Need Conversions
   •  Or create custom namespace
<bean class="de.adesso....ScalaBean">	
  <property name="list" >	
    <scala:list >	
      <value type="java.lang.Integer">42</value>	
    </scala:list>	
  </property>	
</bean>
Spring JavaConfig
•  Allows the definition of Spring Beans
   using Java classes
•  Classes contain code to create Spring
   Beans
•  Still conforms to Spring Bean rules
  –  Singleton, AOP, autowiring etc
•  Can be used with Scala
Spring JavaConfig with Scala
@Configuration	
class ScalaConfig {	 Defined in
	                    XML
  @Autowired	
  var dataSource: DataSource = _	
	
  @Bean	                        Not really
  def transactionManager() =	 elegant..
    new DataSourceTransactionManager(dataSource)	
	
  @Bean	
  def customerDAO() = new CustomerDAO(dataSource)	
}
Spring JavaConfig
•  Almost like a Spring Configuration DSL
•  No need for Spring Scala DSL (?)
•  Full power of Scala for creating objects
•  Can also add configuration for value from
   properties files etc
•  Also nice for infrastructure

•  But reconfiguration = recompiling and
   redeployment
Annotations
•  Annotate classes
•  Classpath scanned for annotated
   classes
•  These become Spring beans
Annotations Code
@Component	
class CustomerDAO {	
	
  @Autowired	
   var dataSource: DataSource = _ 	
	
}
<beans ... >	
<context:component-scan	
   base-package="de.adesso.scalaspring.dao" />
Annotations Code
@Component	
class CustomerDAO(dataSource: DataSource) {	
}




<beans ... default-autowire="constructor">	
<context:component-scan	
  base-package="de.adesso.scalaspring.dao" />
Naming Convention

 No annotations – just a naming convention

class CustomerDAO(dataSource: DataSource) {	
}

<context:component-scan	
  base-package="de.adesso.scalaspring.dao"	
  use-default-filters="false">	
    <context:include-filter type="regex"	
      expression=".*DAO" />	
</context:component-scan>
Service Abstraction
Service Abstraction
•  Example: JDBC
•  Common advantages:
  –  Runtime exceptions instead of checked
     exceptions
  –  Uniform API (e.g. transactions)
  –  Resource handling solved
Service Abstraction: Code
 •  Works out of the box
 •  However, needs Java type issues (Integer)
class CustomerDAO(dataSource: DataSource) {	
   	
   val jdbcTemplate = new JdbcTemplate(dataSource)	
	
  def deleteById(id: Int) =	
     jdbcTemplate.update(	
      "DELETE FROM CUSTOMER WHERE ID=?",	
      id : java.lang.Integer)	
}
More Complex
•    How can one access a ResultSet?
•    Resource handled by JDBC
•    Cannot return it – it has to be closed
•    Solution: callback
•    …and inner class
Callbacks in Java
public class CustomerDAO extends SimpleJdbcDaoSupport {	
	
   private static final class CustomerResultSetRowMapper	
      implements ParameterizedRowMapper<Customer> {	
        public Customer mapRow(ResultSet rs, int rowNum) {	
          Customer customer = new Customer(rs.getString(1),	
             rs.getString(2), rs.getDouble(4));	
          customer.setId(rs.getInt(3));	
          return customer;	
        	}	
   }	
	
   public List<Customer> getByName(String name) {	
      return getSimpleJdbcTemplate()	
        .query(	
            "SELECT * FROM T_CUSTOMER WHERE NAME=?",	
            new CustomerResultSetRowMapper(), name);	
   }	
}
Callbacks in Scala
•  Callbacks are really functions
•  Called on each row

•  Use template with Scala function?
Callback in Scala
def findById(id: Int): Option[Customer] = {	
  val result: Buffer[Customer] =	
   jdbcTemplate.query(	
     "SELECT * FROM CUSTOMER C WHERE C.ID=?",	
      (rs: ResultSet) => {	
        Customer(rs.getInt(1), rs.getString(2),	
          rs.getString(3), rs.getDouble(4))	
      },	
      id : java.lang.Integer)	
    result.headOption	
}
Behind the Scenes: Implicit
  •  Converts a function into a callback
     object
  •  Transparently behind the scenes
implicit def rowMapperImplicit[T](	
  func: (ResultSet) => T) = {	
     new RowMapper[T] {	
       def mapRow(rs: ResultSet, rowNum: Int) 	
         = func(rs).asInstanceOf[T]	
  }	
}
Some Problems
•  Scala value types and collections must
   be converted to Java objects (i.e. Int to
   Integer)
•  null instead of Option[T]
•  classOf[T] instead of plain type

•  Wrapper would be more natural but
   more effort
Aspect Oriented Programming
Why AOP?
•  Centralized implementation of cross
   cutting concerns
•  E.g. security, transactions, tracing..
•  Aspect =
  –  Advice : executed code
  –  Pointcut : where the code is executed


•  Let’s see some Pointcut expressions…
execution(void hello())


Execution of method hello, no parameters, void return type
execution(int com.ewolff.Service.hello(int))


Execution of method hello in class Service in package com.ewolff
              one int as parameters, int return type
execution(* *Service.*(..))
      Execution of any method in class with suffix
      Any number of parameters, any return type
                     Any Service
             i.e. add behavior to every service
                    (security, transaction)

             Defines what constitutes a service

             Proper and orderly usage of AOP
AOP Example
@Aspect	
public class TracingAspect {	
	
     	@Before("execution(* com.ewolff.highscore..*.*(..))")	
     	public void traceEnter(JoinPoint joinPoint) {	
     	     	System.out.println("enter "+joinPoint);	
     	}	
     		
	
     	@After("execution(* com.ewolff.highscore..*.*(..))")	
     	public void traceExit(JoinPoint joinPoint) {	
     	     	System.out.println("exit "+joinPoint);	
     	}	
	
}
Problems
•    Must provide parameter less constructor
•    Pointcut depends on Java type system
•    Scala has a different type system
•    Can combine Scala + Spring AOP
     –  Use bean Pointcut:
        bean(aVerySpecificBean)
        bean(*DAO)
     –  Or Annotations:
        execution(@retry.Retry * *(..))
AOP and Scala: 2nd Thought
•  Spring AOP is not efficient
•  Method calls are done dynamically
•  AspectJ will make project setup too
   complex
•  A modern programming language
   should handle cross cutting concerns
•  E.g. meta programming in dynamic
   languages
•  Can we do better?
Functions
•  Can use functions to “wrap” methods,
   blocks and functions and do
   transactions
•  Based on TransactionTemplate
   and callbacks
Code
implicit def txCallbackImplicit[T](func: => T)…	
	
def transactional[T](	
  propagation: Propagation = Propagation.REQUIRED,	
  …)	
  (func: => T): T = {	
   val txAttribute = 	
    new TransactionAttributeWithRollbackRules(	
      propagation,…)	
    val txTemplate =	
    new TransactionTemplate(txManager,txAttribute)	
      txTemplate.execute(func)	
}
Usage
 •  Can be used to wrap any code block
 •  Not just methods
 •  But: No way to make a whole class /
    system transactional

transactional(propagation = 	
  Propagation.REQUIRES_NEW) {	
   customerDAO.save(	
    Customer(0, "Wolff", "Eberhard", 42.0))	
   throw new RuntimeException()	
}
Testing
Testing in Spring
•  Injection in Test classes

•  Transaction handling
  –  Start a transaction for each test method
  –  At the end of the method: Rollback
•  Benefit: No need to clean up the
   database
•  Good start: No production code in Scala
Testing with JUnit 4, Spring
             and Scala
@RunWith(classOf[SpringJUnit4ClassRunner])	
@Transactional	
@ContextConfiguration(	
Array("/spring/scalaSpringConfig.xml"))	
class CustomerDAOTest extends Config {	
   @Autowired	
   var customerDAO : CustomerDAO = null	
   @Test	
   def testSaveDelete() {	
     val numberOfCustomersBefore =	
       customerDAO.count()	
   …}	
}
Sum Up
Sum Up
•  Scala and Spring are a good match
•  Spring is very adaptable
•  Dependency Injection
  –  Works, some improvements possible
•  Service Abstraction
  –  Functions are a good fit
•  AOP
  –  Can work with Scala but not ideal
  –  Scala can do similar things with functions
Potential Improvements
•  Dependency Injection
  –  Support for all Scala collections
  –  Support for Scala properties
  –  Support for Scala singletons
  –  Conversions for all basic Scala types
  –  Spring configuration DSL
•  Service Abstraction
  –  Provide implicits for all callbacks
Potential Improvements
•  AOP
  –  Provide functions for all common aspects
•  Testing
  –  Support Scala test frameworks
  –  http://www.cakesolutions.org/specs2-
     spring.html
Links
•  https://github.com/ewolff/scala-spring
•  Request for Scala version of Spring (only 12 votes)
   https://jira.springsource.org/browse/SPR-7876
•  Scala and AspectJ: Approaching modularization of crosscutting
   functionalities
   http://days2011.scala-lang.org/sites/days2011/files/
   52.%20AspectJ.pdf
•  Sample for Spring Security and Scala
    https://github.com/tekul/scalasec
•  Spring Integration Scala DSL
   https://github.com/SpringSource/spring-integration-scala
•  (German) Thesis about Scala & Lift vs. Java EE:
   http://www.slideshare.net/adessoAG/vergleich-des-scala-
   webframeworks-lift-mit-dem-java-ee-programmiermodell
•  (German) Thesis about Scala, JSF and Hibernate:
   http://www.slideshare.net/bvonkalm/thesis-5821628

More Related Content

PDF
Scala @ TechMeetup Edinburgh
ODP
Refactoring to Scala DSLs and LiftOff 2009 Recap
PDF
JavaCro 2014 Scala and Java EE 7 Development Experiences
KEY
Scala for scripting
PDF
A Brief, but Dense, Intro to Scala
PDF
BOF2644 Developing Java EE 7 Scala apps
PPT
Scala in a nutshell by venkat
PPT
55 New Features in Java 7
Scala @ TechMeetup Edinburgh
Refactoring to Scala DSLs and LiftOff 2009 Recap
JavaCro 2014 Scala and Java EE 7 Development Experiences
Scala for scripting
A Brief, but Dense, Intro to Scala
BOF2644 Developing Java EE 7 Scala apps
Scala in a nutshell by venkat
55 New Features in Java 7

What's hot (20)

PDF
Scala coated JVM
PDF
QCon 2015 Scala for the Enterprise: Get FuNkEd Up on the JVM
PDF
Naver_alternative_to_jpa
PPTX
Кирилл Безпалый, .NET Developer, Ciklum
PPTX
From Ruby to Scala
PDF
CBStreams - Java Streams for ColdFusion (CFML)
PPTX
A brief tour of modern Java
PDF
Alternatives of JPA/Hibernate
PPTX
Java 8 Features
PDF
2018 05-16 Evolving Technologies: React, Babel & Webpack
PPTX
55 New Features in Java SE 8
PDF
Introduction to Functional Programming with Scala
PDF
Solid And Sustainable Development in Scala
PDF
The Evolution of Scala / Scala進化論
KEY
The Why and How of Scala at Twitter
PDF
Connect.Tech- Enhancing Your Workflow With Xcode Source Editor Extensions
PDF
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
PDF
Quick introduction to scala
PPTX
Demystifying Oak Search
PDF
Spring data requery
Scala coated JVM
QCon 2015 Scala for the Enterprise: Get FuNkEd Up on the JVM
Naver_alternative_to_jpa
Кирилл Безпалый, .NET Developer, Ciklum
From Ruby to Scala
CBStreams - Java Streams for ColdFusion (CFML)
A brief tour of modern Java
Alternatives of JPA/Hibernate
Java 8 Features
2018 05-16 Evolving Technologies: React, Babel & Webpack
55 New Features in Java SE 8
Introduction to Functional Programming with Scala
Solid And Sustainable Development in Scala
The Evolution of Scala / Scala進化論
The Why and How of Scala at Twitter
Connect.Tech- Enhancing Your Workflow With Xcode Source Editor Extensions
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
Quick introduction to scala
Demystifying Oak Search
Spring data requery
Ad

Viewers also liked (20)

PDF
Using Open Source technologies to create Enterprise Level Cloud System
ODP
Lengua anuncio
PDF
Hum2310 sm2015 proust questionnaire
PDF
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen
PPTX
Fiesta de Disfraces
PDF
Tsahim 1
PDF
PPTX
What DevOps can learn from Oktoberfest
PDF
Why i want to work in a call center (and why i ultimately don't)
PDF
Ruolo dello stress ossidativo nei vari stadi della psoriasi
PPTX
KEPERCAYAAN GURU
PPTX
Health Status of Children in Isabel, Leyte
PPTX
PDF
Hum1020 fa2014 exam 4 study guide
PPTX
Alberti Center Sample Presentation for Parents
PDF
SharePoint TechCon 2009 - 907
PDF
Computerworld Honors Direct Relief Case Study
PDF
Hum2220 sm2015 syllabus
PPTX
Exploring Cloud Credentials for Institutional Use
Using Open Source technologies to create Enterprise Level Cloud System
Lengua anuncio
Hum2310 sm2015 proust questionnaire
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen
Fiesta de Disfraces
Tsahim 1
What DevOps can learn from Oktoberfest
Why i want to work in a call center (and why i ultimately don't)
Ruolo dello stress ossidativo nei vari stadi della psoriasi
KEPERCAYAAN GURU
Health Status of Children in Isabel, Leyte
Hum1020 fa2014 exam 4 study guide
Alberti Center Sample Presentation for Parents
SharePoint TechCon 2009 - 907
Computerworld Honors Direct Relief Case Study
Hum2220 sm2015 syllabus
Exploring Cloud Credentials for Institutional Use
Ad

Similar to Spring Day | Spring and Scala | Eberhard Wolff (20)

PDF
Scala and Spring
PDF
Spring db-access mod03
PDF
MongoDB for Java Developers with Spring Data
PPTX
Spring Basics
PPTX
Spring framework part 2
PPTX
Ups and downs of enterprise Java app in a research setting
PDF
MongoDB for Java Devs with Spring Data - MongoPhilly 2011
PDF
Spring framework
PPT
Spring - a framework written by developers
PPTX
An Intro to Scala for PHP Developers
PPT
Spring ppt
PDF
Spring scala - Sneaking Scala into your corporation
PPT
Hybernat and structs, spring classes in mumbai
PDF
Spring Framework Tutorial | VirtualNuggets
PPTX
Java 8 and beyond, a scala story
PDF
PDF
Rafael Bagmanov «Scala in a wild enterprise»
KEY
A Walking Tour of (almost) all of Springdom
DOCX
Spring notes
PPTX
Spring Data - Intro (Odessa Java TechTalks)
Scala and Spring
Spring db-access mod03
MongoDB for Java Developers with Spring Data
Spring Basics
Spring framework part 2
Ups and downs of enterprise Java app in a research setting
MongoDB for Java Devs with Spring Data - MongoPhilly 2011
Spring framework
Spring - a framework written by developers
An Intro to Scala for PHP Developers
Spring ppt
Spring scala - Sneaking Scala into your corporation
Hybernat and structs, spring classes in mumbai
Spring Framework Tutorial | VirtualNuggets
Java 8 and beyond, a scala story
Rafael Bagmanov «Scala in a wild enterprise»
A Walking Tour of (almost) all of Springdom
Spring notes
Spring Data - Intro (Odessa Java TechTalks)

More from JAX London (20)

PDF
Java Tech & Tools | Continuous Delivery - the Writing is on the Wall | John S...
ODP
Java Tech & Tools | Mapping, GIS and Geolocating Data in Java | Joachim Van d...
PDF
Keynote | Middleware Everywhere - Ready for Mobile and Cloud | Dr. Mark Little
PDF
Spring Day | WaveMaker - Spring Roo - SpringSource Tool Suite: Choosing the R...
PDF
Spring Day | Behind the Scenes at Spring Batch | Dave Syer
PDF
Spring Day | Identity Management with Spring Security | Dave Syer
PDF
Spring Day | Data Access 2.0? Please Welcome Spring Data! | Oliver Gierke
PPT
Keynote | The Rise and Fall and Rise of Java | James Governor
ODP
Java Tech & Tools | OSGi Best Practices | Emily Jiang
PPTX
Java Tech & Tools | Beyond the Data Grid: Coherence, Normalisation, Joins and...
PDF
Java Tech & Tools | Big Blobs: Moving Big Data In and Out of the Cloud | Adri...
PDF
Java Tech & Tools | Social Media in Programming in Java | Khanderao Kand
PDF
Java Tech & Tools | Just Keep Passing the Message | Russel Winder
PDF
Java Tech & Tools | Grails in the Java Enterprise | Peter Ledbrook
PDF
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
ODP
Java EE | Modular EJBs for Enterprise OSGi | Tim Ward
PDF
Java EE | Apache TomEE - Java EE Web Profile on Tomcat | Jonathan Gallimore
KEY
Java Core | Understanding the Disruptor: a Beginner's Guide to Hardcore Concu...
PDF
Java Core | Java 8 and OSGi Modularisation | Tim Ellison & Neil Bartlett
PPTX
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
Java Tech & Tools | Continuous Delivery - the Writing is on the Wall | John S...
Java Tech & Tools | Mapping, GIS and Geolocating Data in Java | Joachim Van d...
Keynote | Middleware Everywhere - Ready for Mobile and Cloud | Dr. Mark Little
Spring Day | WaveMaker - Spring Roo - SpringSource Tool Suite: Choosing the R...
Spring Day | Behind the Scenes at Spring Batch | Dave Syer
Spring Day | Identity Management with Spring Security | Dave Syer
Spring Day | Data Access 2.0? Please Welcome Spring Data! | Oliver Gierke
Keynote | The Rise and Fall and Rise of Java | James Governor
Java Tech & Tools | OSGi Best Practices | Emily Jiang
Java Tech & Tools | Beyond the Data Grid: Coherence, Normalisation, Joins and...
Java Tech & Tools | Big Blobs: Moving Big Data In and Out of the Cloud | Adri...
Java Tech & Tools | Social Media in Programming in Java | Khanderao Kand
Java Tech & Tools | Just Keep Passing the Message | Russel Winder
Java Tech & Tools | Grails in the Java Enterprise | Peter Ledbrook
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
Java EE | Modular EJBs for Enterprise OSGi | Tim Ward
Java EE | Apache TomEE - Java EE Web Profile on Tomcat | Jonathan Gallimore
Java Core | Understanding the Disruptor: a Beginner's Guide to Hardcore Concu...
Java Core | Java 8 and OSGi Modularisation | Tim Ellison & Neil Bartlett
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter

Recently uploaded (20)

PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Electronic commerce courselecture one. Pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
KodekX | Application Modernization Development
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PPTX
Spectroscopy.pptx food analysis technology
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Big Data Technologies - Introduction.pptx
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
Empathic Computing: Creating Shared Understanding
PDF
Machine learning based COVID-19 study performance prediction
PPT
Teaching material agriculture food technology
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Electronic commerce courselecture one. Pdf
The AUB Centre for AI in Media Proposal.docx
Review of recent advances in non-invasive hemoglobin estimation
Dropbox Q2 2025 Financial Results & Investor Presentation
KodekX | Application Modernization Development
Reach Out and Touch Someone: Haptics and Empathic Computing
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Diabetes mellitus diagnosis method based random forest with bat algorithm
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Spectroscopy.pptx food analysis technology
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
20250228 LYD VKU AI Blended-Learning.pptx
Big Data Technologies - Introduction.pptx
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
Empathic Computing: Creating Shared Understanding
Machine learning based COVID-19 study performance prediction
Teaching material agriculture food technology

Spring Day | Spring and Scala | Eberhard Wolff

  • 1. Scala and Spring Eberhard Wolff Architecture and Technology Manager adesso AG, Germany
  • 2. Why Scala and Spring? •  Scala •  Spring –  Strongly typed –  The tools for language enterprise apps –  Elegant –  Well established –  Functional –  Lots of know how programming –  Very flexible –  Focus on Concurrency –  Lack of enterprise frameworks
  • 3. Spring‘s Core Elements •  Dependency Injection –  Organize the collaboration of objects •  Aspect Oriented Programming –  Handle cross cutting concerns like security or transactions •  Portable Service Abstraction –  Easy, unified APIs for JMS, JDBC, tx … •  Testing •  How can they be used with Scala?
  • 5. Dependency Injection •  Depended objects are injected •  Advantages: –  Better handling of dependencies –  Easier testability –  Easier configuration
  • 6. Dependency Injection •  Dependency Injection is a Pattern •  i.e. you can implement it in code •  …and therefore in plain Scala •  Configuration in a file: more flexibility –  No compile / redeploy –  Configure values, not just references •  Spring offers a lot of approaches to DI
  • 7. Example •  DAO depends on a DataSource •  Injected in the constructor •  Matches Scala’s immutability approach class CustomerDAO(dataSource: DataSource) { val jdbcTemplate = new JdbcTemplate(dataSource) ... }
  • 8. On Singletons •  Scala introduces objects as Singletons •  Example uses Scala classes •  Spring needs to do the creation so Dependency Injection can be done •  Might consider @Configurable but that adds AspectJ Load Time Weaving… •  More flexibility concerning scopes
  • 9. Spring XML Configuration <beans ...> <jdbc:embedded-database type="HSQL" id="dataSource" /> <bean id="customerDAO" class="de.adesso.scalaspring.dao.CustomerDAO"> <constructor-arg ref="dataSource" /> </bean> </beans>
  • 10. Spring XML Configuration •  Very easy and little difference to Java •  For optional configuration: Use @BeanProperty to generate getters and setters •  Marks property as configurable by Spring •  Might want to create your own Conversions to configure Scala types
  • 11. Spring XML & Scala Collections •  Scala has its own collection classes •  Cannot be configured with Spring XML out of the box •  Need Conversions •  Or create custom namespace <bean class="de.adesso....ScalaBean"> <property name="list" > <scala:list > <value type="java.lang.Integer">42</value> </scala:list> </property> </bean>
  • 12. Spring JavaConfig •  Allows the definition of Spring Beans using Java classes •  Classes contain code to create Spring Beans •  Still conforms to Spring Bean rules –  Singleton, AOP, autowiring etc •  Can be used with Scala
  • 13. Spring JavaConfig with Scala @Configuration class ScalaConfig { Defined in XML @Autowired var dataSource: DataSource = _ @Bean Not really def transactionManager() = elegant.. new DataSourceTransactionManager(dataSource) @Bean def customerDAO() = new CustomerDAO(dataSource) }
  • 14. Spring JavaConfig •  Almost like a Spring Configuration DSL •  No need for Spring Scala DSL (?) •  Full power of Scala for creating objects •  Can also add configuration for value from properties files etc •  Also nice for infrastructure •  But reconfiguration = recompiling and redeployment
  • 15. Annotations •  Annotate classes •  Classpath scanned for annotated classes •  These become Spring beans
  • 16. Annotations Code @Component class CustomerDAO { @Autowired var dataSource: DataSource = _ } <beans ... > <context:component-scan base-package="de.adesso.scalaspring.dao" />
  • 17. Annotations Code @Component class CustomerDAO(dataSource: DataSource) { } <beans ... default-autowire="constructor"> <context:component-scan base-package="de.adesso.scalaspring.dao" />
  • 18. Naming Convention No annotations – just a naming convention class CustomerDAO(dataSource: DataSource) { } <context:component-scan base-package="de.adesso.scalaspring.dao" use-default-filters="false"> <context:include-filter type="regex" expression=".*DAO" /> </context:component-scan>
  • 20. Service Abstraction •  Example: JDBC •  Common advantages: –  Runtime exceptions instead of checked exceptions –  Uniform API (e.g. transactions) –  Resource handling solved
  • 21. Service Abstraction: Code •  Works out of the box •  However, needs Java type issues (Integer) class CustomerDAO(dataSource: DataSource) { val jdbcTemplate = new JdbcTemplate(dataSource) def deleteById(id: Int) = jdbcTemplate.update( "DELETE FROM CUSTOMER WHERE ID=?", id : java.lang.Integer) }
  • 22. More Complex •  How can one access a ResultSet? •  Resource handled by JDBC •  Cannot return it – it has to be closed •  Solution: callback •  …and inner class
  • 23. Callbacks in Java public class CustomerDAO extends SimpleJdbcDaoSupport { private static final class CustomerResultSetRowMapper implements ParameterizedRowMapper<Customer> { public Customer mapRow(ResultSet rs, int rowNum) { Customer customer = new Customer(rs.getString(1), rs.getString(2), rs.getDouble(4)); customer.setId(rs.getInt(3)); return customer; } } public List<Customer> getByName(String name) { return getSimpleJdbcTemplate() .query( "SELECT * FROM T_CUSTOMER WHERE NAME=?", new CustomerResultSetRowMapper(), name); } }
  • 24. Callbacks in Scala •  Callbacks are really functions •  Called on each row •  Use template with Scala function?
  • 25. Callback in Scala def findById(id: Int): Option[Customer] = { val result: Buffer[Customer] = jdbcTemplate.query( "SELECT * FROM CUSTOMER C WHERE C.ID=?", (rs: ResultSet) => { Customer(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getDouble(4)) }, id : java.lang.Integer) result.headOption }
  • 26. Behind the Scenes: Implicit •  Converts a function into a callback object •  Transparently behind the scenes implicit def rowMapperImplicit[T]( func: (ResultSet) => T) = { new RowMapper[T] { def mapRow(rs: ResultSet, rowNum: Int) = func(rs).asInstanceOf[T] } }
  • 27. Some Problems •  Scala value types and collections must be converted to Java objects (i.e. Int to Integer) •  null instead of Option[T] •  classOf[T] instead of plain type •  Wrapper would be more natural but more effort
  • 29. Why AOP? •  Centralized implementation of cross cutting concerns •  E.g. security, transactions, tracing.. •  Aspect = –  Advice : executed code –  Pointcut : where the code is executed •  Let’s see some Pointcut expressions…
  • 30. execution(void hello()) Execution of method hello, no parameters, void return type
  • 31. execution(int com.ewolff.Service.hello(int)) Execution of method hello in class Service in package com.ewolff one int as parameters, int return type
  • 32. execution(* *Service.*(..)) Execution of any method in class with suffix Any number of parameters, any return type Any Service i.e. add behavior to every service (security, transaction) Defines what constitutes a service Proper and orderly usage of AOP
  • 33. AOP Example @Aspect public class TracingAspect { @Before("execution(* com.ewolff.highscore..*.*(..))") public void traceEnter(JoinPoint joinPoint) { System.out.println("enter "+joinPoint); } @After("execution(* com.ewolff.highscore..*.*(..))") public void traceExit(JoinPoint joinPoint) { System.out.println("exit "+joinPoint); } }
  • 34. Problems •  Must provide parameter less constructor •  Pointcut depends on Java type system •  Scala has a different type system •  Can combine Scala + Spring AOP –  Use bean Pointcut: bean(aVerySpecificBean) bean(*DAO) –  Or Annotations: execution(@retry.Retry * *(..))
  • 35. AOP and Scala: 2nd Thought •  Spring AOP is not efficient •  Method calls are done dynamically •  AspectJ will make project setup too complex •  A modern programming language should handle cross cutting concerns •  E.g. meta programming in dynamic languages •  Can we do better?
  • 36. Functions •  Can use functions to “wrap” methods, blocks and functions and do transactions •  Based on TransactionTemplate and callbacks
  • 37. Code implicit def txCallbackImplicit[T](func: => T)… def transactional[T]( propagation: Propagation = Propagation.REQUIRED, …) (func: => T): T = { val txAttribute = new TransactionAttributeWithRollbackRules( propagation,…) val txTemplate = new TransactionTemplate(txManager,txAttribute) txTemplate.execute(func) }
  • 38. Usage •  Can be used to wrap any code block •  Not just methods •  But: No way to make a whole class / system transactional transactional(propagation = Propagation.REQUIRES_NEW) { customerDAO.save( Customer(0, "Wolff", "Eberhard", 42.0)) throw new RuntimeException() }
  • 40. Testing in Spring •  Injection in Test classes •  Transaction handling –  Start a transaction for each test method –  At the end of the method: Rollback •  Benefit: No need to clean up the database •  Good start: No production code in Scala
  • 41. Testing with JUnit 4, Spring and Scala @RunWith(classOf[SpringJUnit4ClassRunner]) @Transactional @ContextConfiguration( Array("/spring/scalaSpringConfig.xml")) class CustomerDAOTest extends Config { @Autowired var customerDAO : CustomerDAO = null @Test def testSaveDelete() { val numberOfCustomersBefore = customerDAO.count() …} }
  • 43. Sum Up •  Scala and Spring are a good match •  Spring is very adaptable •  Dependency Injection –  Works, some improvements possible •  Service Abstraction –  Functions are a good fit •  AOP –  Can work with Scala but not ideal –  Scala can do similar things with functions
  • 44. Potential Improvements •  Dependency Injection –  Support for all Scala collections –  Support for Scala properties –  Support for Scala singletons –  Conversions for all basic Scala types –  Spring configuration DSL •  Service Abstraction –  Provide implicits for all callbacks
  • 45. Potential Improvements •  AOP –  Provide functions for all common aspects •  Testing –  Support Scala test frameworks –  http://www.cakesolutions.org/specs2- spring.html
  • 46. Links •  https://github.com/ewolff/scala-spring •  Request for Scala version of Spring (only 12 votes) https://jira.springsource.org/browse/SPR-7876 •  Scala and AspectJ: Approaching modularization of crosscutting functionalities http://days2011.scala-lang.org/sites/days2011/files/ 52.%20AspectJ.pdf •  Sample for Spring Security and Scala https://github.com/tekul/scalasec •  Spring Integration Scala DSL https://github.com/SpringSource/spring-integration-scala •  (German) Thesis about Scala & Lift vs. Java EE: http://www.slideshare.net/adessoAG/vergleich-des-scala- webframeworks-lift-mit-dem-java-ee-programmiermodell •  (German) Thesis about Scala, JSF and Hibernate: http://www.slideshare.net/bvonkalm/thesis-5821628