SlideShare ist ein Scribd-Unternehmen logo
1 von 46
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

QCon 2015 Scala for the Enterprise: Get FuNkEd Up on the JVM
QCon 2015 Scala for the Enterprise: Get FuNkEd Up on the JVMQCon 2015 Scala for the Enterprise: Get FuNkEd Up on the JVM
QCon 2015 Scala for the Enterprise: Get FuNkEd Up on the JVM
Peter Pilgrim
 
Кирилл Безпалый, .NET Developer, Ciklum
Кирилл Безпалый, .NET Developer, CiklumКирилл Безпалый, .NET Developer, Ciklum
Кирилл Безпалый, .NET Developer, Ciklum
Alina Vilk
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
pramode_ce
 

Was ist angesagt? (20)

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

Andere mochten auch

Lengua anuncio
Lengua anuncioLengua anuncio
Lengua anuncio
franky226
 
Hum2310 sm2015 proust questionnaire
Hum2310 sm2015 proust questionnaireHum2310 sm2015 proust questionnaire
Hum2310 sm2015 proust questionnaire
ProfWillAdams
 
Health Status of Children in Isabel, Leyte
Health Status of Children in Isabel, LeyteHealth Status of Children in Isabel, Leyte
Health Status of Children in Isabel, Leyte
Marc Macalua
 
Hum1020 fa2014 exam 4 study guide
Hum1020 fa2014 exam 4 study guideHum1020 fa2014 exam 4 study guide
Hum1020 fa2014 exam 4 study guide
ProfWillAdams
 
SharePoint TechCon 2009 - 907
SharePoint TechCon 2009 - 907SharePoint TechCon 2009 - 907
SharePoint TechCon 2009 - 907
Andreas Grabner
 
Computerworld Honors Direct Relief Case Study
Computerworld Honors Direct Relief Case StudyComputerworld Honors Direct Relief Case Study
Computerworld Honors Direct Relief Case Study
Direct Relief
 
Hum2220 sm2015 syllabus
Hum2220 sm2015 syllabusHum2220 sm2015 syllabus
Hum2220 sm2015 syllabus
ProfWillAdams
 

Andere mochten auch (20)

Using Open Source technologies to create Enterprise Level Cloud System
Using Open Source technologies to create Enterprise Level Cloud SystemUsing Open Source technologies to create Enterprise Level Cloud System
Using Open Source technologies to create Enterprise Level Cloud System
 
Lengua anuncio
Lengua anuncioLengua anuncio
Lengua anuncio
 
Hum2310 sm2015 proust questionnaire
Hum2310 sm2015 proust questionnaireHum2310 sm2015 proust questionnaire
Hum2310 sm2015 proust questionnaire
 
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen
Spring Day | Spring 3.1 in a Nutshell | Sam BrannenSpring Day | Spring 3.1 in a Nutshell | Sam Brannen
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen
 
Fiesta de Disfraces
Fiesta de DisfracesFiesta de Disfraces
Fiesta de Disfraces
 
Tsahim 1
Tsahim 1Tsahim 1
Tsahim 1
 
Aesaes
AesaesAesaes
Aesaes
 
What DevOps can learn from Oktoberfest
What DevOps can learn from OktoberfestWhat DevOps can learn from Oktoberfest
What DevOps can learn from Oktoberfest
 
Why i want to work in a call center (and why i ultimately don't)
Why i want to work in a call center (and why i ultimately don't)Why i want to work in a call center (and why i ultimately don't)
Why i want to work in a call center (and why i ultimately don't)
 
Ruolo dello stress ossidativo nei vari stadi della psoriasi
Ruolo dello stress ossidativo nei vari stadi della psoriasiRuolo dello stress ossidativo nei vari stadi della psoriasi
Ruolo dello stress ossidativo nei vari stadi della psoriasi
 
KEPERCAYAAN GURU
KEPERCAYAAN GURU KEPERCAYAAN GURU
KEPERCAYAAN GURU
 
Health Status of Children in Isabel, Leyte
Health Status of Children in Isabel, LeyteHealth Status of Children in Isabel, Leyte
Health Status of Children in Isabel, Leyte
 
ΠΔ126
ΠΔ126ΠΔ126
ΠΔ126
 
Interrupt jhc
Interrupt jhcInterrupt jhc
Interrupt jhc
 
Hum1020 fa2014 exam 4 study guide
Hum1020 fa2014 exam 4 study guideHum1020 fa2014 exam 4 study guide
Hum1020 fa2014 exam 4 study guide
 
Alberti Center Sample Presentation for Parents
Alberti Center Sample Presentation for ParentsAlberti Center Sample Presentation for Parents
Alberti Center Sample Presentation for Parents
 
SharePoint TechCon 2009 - 907
SharePoint TechCon 2009 - 907SharePoint TechCon 2009 - 907
SharePoint TechCon 2009 - 907
 
Computerworld Honors Direct Relief Case Study
Computerworld Honors Direct Relief Case StudyComputerworld Honors Direct Relief Case Study
Computerworld Honors Direct Relief Case Study
 
Hum2220 sm2015 syllabus
Hum2220 sm2015 syllabusHum2220 sm2015 syllabus
Hum2220 sm2015 syllabus
 
Exploring Cloud Credentials for Institutional Use
Exploring Cloud Credentials for Institutional UseExploring Cloud Credentials for Institutional Use
Exploring Cloud Credentials for Institutional Use
 

Ähnlich wie Spring Day | Spring and Scala | Eberhard Wolff

Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla
 
Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and Play
Luka Zakrajšek
 

Ähnlich wie Spring Day | Spring and Scala | Eberhard Wolff (20)

Scala and Spring
Scala and SpringScala and Spring
Scala and Spring
 
Couchbas for dummies
Couchbas for dummiesCouchbas for dummies
Couchbas for dummies
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
Wider than rails
Wider than railsWider than rails
Wider than rails
 
Analytics Metrics delivery and ML Feature visualization: Evolution of Data Pl...
Analytics Metrics delivery and ML Feature visualization: Evolution of Data Pl...Analytics Metrics delivery and ML Feature visualization: Evolution of Data Pl...
Analytics Metrics delivery and ML Feature visualization: Evolution of Data Pl...
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentation
 
jQuery Objects
jQuery ObjectsjQuery Objects
jQuery Objects
 
Scala active record
Scala active recordScala active record
Scala active record
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and Play
 
How Scala promotes TDD
How Scala promotes TDDHow Scala promotes TDD
How Scala promotes TDD
 
The Pushdown of Everything by Stephan Kessler and Santiago Mola
The Pushdown of Everything by Stephan Kessler and Santiago MolaThe Pushdown of Everything by Stephan Kessler and Santiago Mola
The Pushdown of Everything by Stephan Kessler and Santiago Mola
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
 
Alberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.jsAlberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.js
 
Scala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJSScala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJS
 
Scala in a wild enterprise
Scala in a wild enterpriseScala in a wild enterprise
Scala in a wild enterprise
 
ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6
 
Google cloud Dataflow & Apache Flink
Google cloud Dataflow & Apache FlinkGoogle cloud Dataflow & Apache Flink
Google cloud Dataflow & Apache Flink
 
Full Stack Scala
Full Stack ScalaFull Stack Scala
Full Stack Scala
 

Mehr von JAX London

Spring Day | Data Access 2.0? Please Welcome Spring Data! | Oliver Gierke
Spring Day | Data Access 2.0? Please Welcome Spring Data! | Oliver GierkeSpring Day | Data Access 2.0? Please Welcome Spring Data! | Oliver Gierke
Spring Day | Data Access 2.0? Please Welcome Spring Data! | Oliver Gierke
JAX London
 
Keynote | The Rise and Fall and Rise of Java | James Governor
Keynote | The Rise and Fall and Rise of Java | James GovernorKeynote | The Rise and Fall and Rise of Java | James Governor
Keynote | The Rise and Fall and Rise of Java | James Governor
JAX London
 
Java Tech & Tools | OSGi Best Practices | Emily Jiang
Java Tech & Tools | OSGi Best Practices | Emily JiangJava Tech & Tools | OSGi Best Practices | Emily Jiang
Java Tech & Tools | OSGi Best Practices | Emily Jiang
JAX London
 
Java Tech & Tools | Big Blobs: Moving Big Data In and Out of the Cloud | Adri...
Java Tech & Tools | Big Blobs: Moving Big Data In and Out of the Cloud | Adri...Java Tech & Tools | Big Blobs: Moving Big Data In and Out of the Cloud | Adri...
Java Tech & Tools | Big Blobs: Moving Big Data In and Out of the Cloud | Adri...
JAX London
 
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
JAX London
 

Mehr von JAX London (20)

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

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

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
 
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
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

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