SlideShare a Scribd company logo
Eberhard Wolff
Architecture and Technology Manager
adesso AG, Germany

Spring und Scala
About me
•    Eberhard Wolff
•    Architecture & Technology Manager at adesso
•    adesso is a leading IT consultancy in Germany
•    Speaker
•    Author (e.g. first German Spring book)
•    Blog: http://ewolff.com
•    Twitter: @ewolff
•    http://slideshare.com/ewolff
•    eberhard.wolff@adesso.de
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
•  XML, JavaConfig and Annotations
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
•  Scala won’t create getter and setter for
   <property >
•  So: Use Scala’s @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))	
      } : RowMapper[Customer]	
      ,id : java.lang.Integer)	
    result.headOption	
}

•  Why can the function be converted in a
   RowMapper?
Implicit Conversions in Scala
implicit def double2int(d:Double): Int = d.toInt	

•  Implicits allow conversion from one type to
   another
•  Example: Double to Int
•  Used any time an Int is needed and a Double
   is provided
•  Can we use implicits to convert a function to
   a callback class?
Implicit for Function to Callback
•  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)	
  }	
}
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 in any package with suffix Service
           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 * *(..))
Transactions with AOP
 @Transactional	
 class CustomerDAO(dataSource: DataSource) {	

     @Transactional	
     def save(customer: Customer): Customer = {	
     }	
 }

•    Spring’s @Transaction annotation
•    AOP is used for transactions and security
•    Mark a method or class as transactional
•    AOP behind the scenes
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
•  TransactionTemplate executes
   callbacks in a transaction
Code
implicit def txCallbackImplicit[T](func: => T)…	
	
	
•  Again implicit
•  Converts a function with return type T to a
   TransactionCallback	
•  Now we need to call the
   TransactionTemplate to provide the
   transaction
•  A function will take the transaction configuration
   and call the passed in function
Code     1st parameter:
                              transaction configuration
def transactional[T]	
( propagation: Propagation = Propagation.REQUIRED,
  …)	2nd parameter: function
(func: => T): T = 	
{	
   val txAttribute = 	
    new TransactionAttributeWithRollbackRules(	
      propagation,…)	
   val txTemplate =	
    new TransactionTemplate(txManager,txAttribute)	
   txTemplate.execute(func)	
}
            Call TransactionTemplate with function
            (converted to TransactionCallback) and
            configuration
Usage
 •  Can wrap methods to make them
    transactional
@Component	
class TxCustomerDAO(dataSource: DataSource) {	
  	
  def save(customer: Customer): Customer =	
     transactional() {	
       jdbcTemplate.update(…);	
  }	
	
}
Usage
 •  Can also be used to wrap any code block
 •  But: No way to make a whole class /
    system transactional

transactional(propagation=Propagation.REQUIRED)	
{	
   customerDAO.save(	
    Customer(0, "Wolff", "Eberhard", 42.0))	
}
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
  –  XML works, some improvements possible
  –  Annotations and JavaConfig: No problems
•  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 Scala collections mostly done
  –  Support for Scala properties (no @BeanProperty)
  –  Support for Scala Objects aka Singletons
  –  Conversions for all basic Scala types
  –  Spring configuration DSL (?)
•  Service Abstraction
  –  Provide implicits for non-JDBC callbacks
Potential Improvements
•  AOP
  –  Provide functions for all common aspects besides
     transaction


•  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 16 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
Wir suchen Sie als
Ø    Software-Architekt (m/w)
Ø    Projektleiter (m/w)
Ø    Senior Software Engineer (m/w)


Ø    Kommen Sie zum Stand und gewinnen Sie ein iPad 2!

  jobs@adesso.de
  www.AAAjobs.de
Ad

More Related Content

What's hot (20)

JavaScript
JavaScriptJavaScript
JavaScript
Sunil OS
 
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
Lukas Eder
 
Mastering Oracle ADF Bindings
Mastering Oracle ADF BindingsMastering Oracle ADF Bindings
Mastering Oracle ADF Bindings
Euegene Fedorenko
 
JavaFX and Scala in the Cloud
JavaFX and Scala in the CloudJavaFX and Scala in the Cloud
JavaFX and Scala in the Cloud
Stephen Chin
 
An introduction to SQLAlchemy
An introduction to SQLAlchemyAn introduction to SQLAlchemy
An introduction to SQLAlchemy
mengukagan
 
Java FX 2.0 - A Developer's Guide
Java FX 2.0 - A Developer's GuideJava FX 2.0 - A Developer's Guide
Java FX 2.0 - A Developer's Guide
Stephen Chin
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
Michele Capra
 
QB Into the Box 2018
QB Into the Box 2018QB Into the Box 2018
QB Into the Box 2018
Ortus Solutions, Corp
 
Download It
Download ItDownload It
Download It
webhostingguy
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
Daniel Ballinger
 
$.get, a Prime on Data Fetching
$.get, a Prime on Data Fetching$.get, a Prime on Data Fetching
$.get, a Prime on Data Fetching
Josh Black
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
Michele Capra
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
Chris Weldon
 
A Spring Data’s Guide to Persistence
A Spring Data’s Guide to PersistenceA Spring Data’s Guide to Persistence
A Spring Data’s Guide to Persistence
VMware Tanzu
 
Physical web
Physical webPhysical web
Physical web
Jeff Prestes
 
SenchaCon 2016: The Once and Future Grid - Nige White
SenchaCon 2016: The Once and Future Grid - Nige WhiteSenchaCon 2016: The Once and Future Grid - Nige White
SenchaCon 2016: The Once and Future Grid - Nige White
Sencha
 
PyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorialPyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorial
jbellis
 
Launching Beeline with Firebase
Launching Beeline with FirebaseLaunching Beeline with Firebase
Launching Beeline with Firebase
Chetan Padia
 
Hibernate in Nutshell
Hibernate in NutshellHibernate in Nutshell
Hibernate in Nutshell
Onkar Deshpande
 
This isn't Richard Stallman's Open Source anymore
This isn't Richard Stallman's Open Source anymoreThis isn't Richard Stallman's Open Source anymore
This isn't Richard Stallman's Open Source anymore
Lukas Eder
 
JavaScript
JavaScriptJavaScript
JavaScript
Sunil OS
 
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
Lukas Eder
 
Mastering Oracle ADF Bindings
Mastering Oracle ADF BindingsMastering Oracle ADF Bindings
Mastering Oracle ADF Bindings
Euegene Fedorenko
 
JavaFX and Scala in the Cloud
JavaFX and Scala in the CloudJavaFX and Scala in the Cloud
JavaFX and Scala in the Cloud
Stephen Chin
 
An introduction to SQLAlchemy
An introduction to SQLAlchemyAn introduction to SQLAlchemy
An introduction to SQLAlchemy
mengukagan
 
Java FX 2.0 - A Developer's Guide
Java FX 2.0 - A Developer's GuideJava FX 2.0 - A Developer's Guide
Java FX 2.0 - A Developer's Guide
Stephen Chin
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
Michele Capra
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
Daniel Ballinger
 
$.get, a Prime on Data Fetching
$.get, a Prime on Data Fetching$.get, a Prime on Data Fetching
$.get, a Prime on Data Fetching
Josh Black
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
Michele Capra
 
A Spring Data’s Guide to Persistence
A Spring Data’s Guide to PersistenceA Spring Data’s Guide to Persistence
A Spring Data’s Guide to Persistence
VMware Tanzu
 
SenchaCon 2016: The Once and Future Grid - Nige White
SenchaCon 2016: The Once and Future Grid - Nige WhiteSenchaCon 2016: The Once and Future Grid - Nige White
SenchaCon 2016: The Once and Future Grid - Nige White
Sencha
 
PyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorialPyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorial
jbellis
 
Launching Beeline with Firebase
Launching Beeline with FirebaseLaunching Beeline with Firebase
Launching Beeline with Firebase
Chetan Padia
 
This isn't Richard Stallman's Open Source anymore
This isn't Richard Stallman's Open Source anymoreThis isn't Richard Stallman's Open Source anymore
This isn't Richard Stallman's Open Source anymore
Lukas Eder
 

Similar to Scala and Spring (20)

Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
JAX London
 
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
Loiane Groner
 
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...
Chester Chen
 
Couchbas for dummies
Couchbas for dummiesCouchbas for dummies
Couchbas for dummies
Qureshi Tehmina
 
Wider than rails
Wider than railsWider than rails
Wider than rails
Alexey Nayden
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
Sunghyouk Bae
 
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
 
Scala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJSScala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJS
Alberto Paro
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
LovelitJose
 
Scala active record
Scala active recordScala active record
Scala active record
鉄平 土佐
 
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
 
Scala in a wild enterprise
Scala in a wild enterpriseScala in a wild enterprise
Scala in a wild enterprise
Rafael Bagmanov
 
jQuery Objects
jQuery ObjectsjQuery Objects
jQuery Objects
Steve Wells
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentation
nrjoshiee
 
Naver_alternative_to_jpa
Naver_alternative_to_jpaNaver_alternative_to_jpa
Naver_alternative_to_jpa
NAVER Engineering
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
lennartkats
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in Scala
Kazuhiro Sera
 
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
Spark Summit
 
Angular 2 Essential Training
Angular 2 Essential Training Angular 2 Essential Training
Angular 2 Essential Training
Patrick Schroeder
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
JAX London
 
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
Loiane Groner
 
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...
Chester Chen
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
Sunghyouk Bae
 
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
 
Scala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJSScala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJS
Alberto Paro
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
LovelitJose
 
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
 
Scala in a wild enterprise
Scala in a wild enterpriseScala in a wild enterprise
Scala in a wild enterprise
Rafael Bagmanov
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentation
nrjoshiee
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
lennartkats
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in Scala
Kazuhiro Sera
 
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
Spark Summit
 
Angular 2 Essential Training
Angular 2 Essential Training Angular 2 Essential Training
Angular 2 Essential Training
Patrick Schroeder
 
Ad

More from Eberhard Wolff (20)

Architectures and Alternatives
Architectures and AlternativesArchitectures and Alternatives
Architectures and Alternatives
Eberhard Wolff
 
Beyond Microservices
Beyond MicroservicesBeyond Microservices
Beyond Microservices
Eberhard Wolff
 
The Frontiers of Continuous Delivery
The Frontiers of Continuous DeliveryThe Frontiers of Continuous Delivery
The Frontiers of Continuous Delivery
Eberhard Wolff
 
Four Times Microservices - REST, Kubernetes, UI Integration, Async
Four Times Microservices - REST, Kubernetes, UI Integration, AsyncFour Times Microservices - REST, Kubernetes, UI Integration, Async
Four Times Microservices - REST, Kubernetes, UI Integration, Async
Eberhard Wolff
 
Microservices - not just with Java
Microservices - not just with JavaMicroservices - not just with Java
Microservices - not just with Java
Eberhard Wolff
 
Deployment - Done Right!
Deployment - Done Right!Deployment - Done Right!
Deployment - Done Right!
Eberhard Wolff
 
Data Architecture not Just for Microservices
Data Architecture not Just for MicroservicesData Architecture not Just for Microservices
Data Architecture not Just for Microservices
Eberhard Wolff
 
How to Split Your System into Microservices
How to Split Your System into MicroservicesHow to Split Your System into Microservices
How to Split Your System into Microservices
Eberhard Wolff
 
Microservices and Self-contained System to Scale Agile
Microservices and Self-contained System to Scale AgileMicroservices and Self-contained System to Scale Agile
Microservices and Self-contained System to Scale Agile
Eberhard Wolff
 
How Small Can Java Microservices Be?
How Small Can Java Microservices Be?How Small Can Java Microservices Be?
How Small Can Java Microservices Be?
Eberhard Wolff
 
Data Architecturen Not Just for Microservices
Data Architecturen Not Just for MicroservicesData Architecturen Not Just for Microservices
Data Architecturen Not Just for Microservices
Eberhard Wolff
 
Microservices: Redundancy=Maintainability
Microservices: Redundancy=MaintainabilityMicroservices: Redundancy=Maintainability
Microservices: Redundancy=Maintainability
Eberhard Wolff
 
Self-contained Systems: A Different Approach to Microservices
Self-contained Systems: A Different Approach to MicroservicesSelf-contained Systems: A Different Approach to Microservices
Self-contained Systems: A Different Approach to Microservices
Eberhard Wolff
 
Microservices Technology Stack
Microservices Technology StackMicroservices Technology Stack
Microservices Technology Stack
Eberhard Wolff
 
Software Architecture for Innovation
Software Architecture for InnovationSoftware Architecture for Innovation
Software Architecture for Innovation
Eberhard Wolff
 
Five (easy?) Steps Towards Continuous Delivery
Five (easy?) Steps Towards Continuous DeliveryFive (easy?) Steps Towards Continuous Delivery
Five (easy?) Steps Towards Continuous Delivery
Eberhard Wolff
 
Nanoservices and Microservices with Java
Nanoservices and Microservices with JavaNanoservices and Microservices with Java
Nanoservices and Microservices with Java
Eberhard Wolff
 
Microservices: Architecture to Support Agile
Microservices: Architecture to Support AgileMicroservices: Architecture to Support Agile
Microservices: Architecture to Support Agile
Eberhard Wolff
 
Microservices: Architecture to scale Agile
Microservices: Architecture to scale AgileMicroservices: Architecture to scale Agile
Microservices: Architecture to scale Agile
Eberhard Wolff
 
Microservices, DevOps, Continuous Delivery – More Than Three Buzzwords
Microservices, DevOps, Continuous Delivery – More Than Three BuzzwordsMicroservices, DevOps, Continuous Delivery – More Than Three Buzzwords
Microservices, DevOps, Continuous Delivery – More Than Three Buzzwords
Eberhard Wolff
 
Architectures and Alternatives
Architectures and AlternativesArchitectures and Alternatives
Architectures and Alternatives
Eberhard Wolff
 
The Frontiers of Continuous Delivery
The Frontiers of Continuous DeliveryThe Frontiers of Continuous Delivery
The Frontiers of Continuous Delivery
Eberhard Wolff
 
Four Times Microservices - REST, Kubernetes, UI Integration, Async
Four Times Microservices - REST, Kubernetes, UI Integration, AsyncFour Times Microservices - REST, Kubernetes, UI Integration, Async
Four Times Microservices - REST, Kubernetes, UI Integration, Async
Eberhard Wolff
 
Microservices - not just with Java
Microservices - not just with JavaMicroservices - not just with Java
Microservices - not just with Java
Eberhard Wolff
 
Deployment - Done Right!
Deployment - Done Right!Deployment - Done Right!
Deployment - Done Right!
Eberhard Wolff
 
Data Architecture not Just for Microservices
Data Architecture not Just for MicroservicesData Architecture not Just for Microservices
Data Architecture not Just for Microservices
Eberhard Wolff
 
How to Split Your System into Microservices
How to Split Your System into MicroservicesHow to Split Your System into Microservices
How to Split Your System into Microservices
Eberhard Wolff
 
Microservices and Self-contained System to Scale Agile
Microservices and Self-contained System to Scale AgileMicroservices and Self-contained System to Scale Agile
Microservices and Self-contained System to Scale Agile
Eberhard Wolff
 
How Small Can Java Microservices Be?
How Small Can Java Microservices Be?How Small Can Java Microservices Be?
How Small Can Java Microservices Be?
Eberhard Wolff
 
Data Architecturen Not Just for Microservices
Data Architecturen Not Just for MicroservicesData Architecturen Not Just for Microservices
Data Architecturen Not Just for Microservices
Eberhard Wolff
 
Microservices: Redundancy=Maintainability
Microservices: Redundancy=MaintainabilityMicroservices: Redundancy=Maintainability
Microservices: Redundancy=Maintainability
Eberhard Wolff
 
Self-contained Systems: A Different Approach to Microservices
Self-contained Systems: A Different Approach to MicroservicesSelf-contained Systems: A Different Approach to Microservices
Self-contained Systems: A Different Approach to Microservices
Eberhard Wolff
 
Microservices Technology Stack
Microservices Technology StackMicroservices Technology Stack
Microservices Technology Stack
Eberhard Wolff
 
Software Architecture for Innovation
Software Architecture for InnovationSoftware Architecture for Innovation
Software Architecture for Innovation
Eberhard Wolff
 
Five (easy?) Steps Towards Continuous Delivery
Five (easy?) Steps Towards Continuous DeliveryFive (easy?) Steps Towards Continuous Delivery
Five (easy?) Steps Towards Continuous Delivery
Eberhard Wolff
 
Nanoservices and Microservices with Java
Nanoservices and Microservices with JavaNanoservices and Microservices with Java
Nanoservices and Microservices with Java
Eberhard Wolff
 
Microservices: Architecture to Support Agile
Microservices: Architecture to Support AgileMicroservices: Architecture to Support Agile
Microservices: Architecture to Support Agile
Eberhard Wolff
 
Microservices: Architecture to scale Agile
Microservices: Architecture to scale AgileMicroservices: Architecture to scale Agile
Microservices: Architecture to scale Agile
Eberhard Wolff
 
Microservices, DevOps, Continuous Delivery – More Than Three Buzzwords
Microservices, DevOps, Continuous Delivery – More Than Three BuzzwordsMicroservices, DevOps, Continuous Delivery – More Than Three Buzzwords
Microservices, DevOps, Continuous Delivery – More Than Three Buzzwords
Eberhard Wolff
 
Ad

Recently uploaded (20)

The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 

Scala and Spring

  • 1. Eberhard Wolff Architecture and Technology Manager adesso AG, Germany Spring und Scala
  • 2. About me •  Eberhard Wolff •  Architecture & Technology Manager at adesso •  adesso is a leading IT consultancy in Germany •  Speaker •  Author (e.g. first German Spring book) •  Blog: http://ewolff.com •  Twitter: @ewolff •  http://slideshare.com/ewolff •  [email protected]
  • 3. 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
  • 4. 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?
  • 6. Dependency Injection •  Depended objects are injected •  Advantages: –  Better handling of dependencies –  Easier testability –  Easier configuration
  • 7. 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 •  XML, JavaConfig and Annotations
  • 8. Example •  DAO depends on a DataSource •  Injected in the constructor •  Matches Scala’s immutability approach class CustomerDAO(dataSource: DataSource) { val jdbcTemplate = new JdbcTemplate(dataSource) ... }
  • 9. 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
  • 10. 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>
  • 11. Spring XML Configuration •  Very easy and little difference to Java •  Scala won’t create getter and setter for <property > •  So: Use Scala’s @BeanProperty to generate getters and setters •  Marks property as configurable by Spring •  Might want to create your own Conversions to configure Scala types
  • 12. 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>
  • 13. 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
  • 14. 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) }
  • 15. 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
  • 16. Annotations •  Annotate classes •  Classpath scanned for annotated classes •  These become Spring beans
  • 17. Annotations Code @Component class CustomerDAO { @Autowired var dataSource: DataSource = _ } <beans ... > <context:component-scan base-package="de.adesso.scalaspring.dao" />
  • 18. Annotations Code @Component class CustomerDAO(dataSource: DataSource) { } <beans ... default-autowire="constructor"> <context:component-scan base-package="de.adesso.scalaspring.dao" />
  • 19. 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>
  • 21. Service Abstraction •  Example: JDBC •  Common advantages: –  Runtime exceptions instead of checked exceptions –  Uniform API (e.g. transactions) –  Resource handling solved
  • 22. 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) }
  • 23. 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
  • 24. 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); } }
  • 25. Callbacks in Scala •  Callbacks are really functions •  Called on each row •  Use template with Scala function?
  • 26. 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)) } : RowMapper[Customer] ,id : java.lang.Integer) result.headOption } •  Why can the function be converted in a RowMapper?
  • 27. Implicit Conversions in Scala implicit def double2int(d:Double): Int = d.toInt •  Implicits allow conversion from one type to another •  Example: Double to Int •  Used any time an Int is needed and a Double is provided •  Can we use implicits to convert a function to a callback class?
  • 28. Implicit for Function to Callback •  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) } }
  • 29. 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
  • 31. 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…
  • 32. execution(void hello()) Execution of method hello, no parameters, void return type
  • 33. 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
  • 34. execution(* *..*Service.*(..)) Execution of any method in class in any package with suffix Service 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
  • 35. 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); } }
  • 36. 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 * *(..))
  • 37. Transactions with AOP @Transactional class CustomerDAO(dataSource: DataSource) { @Transactional def save(customer: Customer): Customer = { } } •  Spring’s @Transaction annotation •  AOP is used for transactions and security •  Mark a method or class as transactional •  AOP behind the scenes
  • 38. 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?
  • 39. Functions •  Can use functions to “wrap” methods, blocks and functions and do transactions •  Based on TransactionTemplate and callbacks •  TransactionTemplate executes callbacks in a transaction
  • 40. Code implicit def txCallbackImplicit[T](func: => T)… •  Again implicit •  Converts a function with return type T to a TransactionCallback •  Now we need to call the TransactionTemplate to provide the transaction •  A function will take the transaction configuration and call the passed in function
  • 41. Code 1st parameter: transaction configuration def transactional[T] ( propagation: Propagation = Propagation.REQUIRED, …) 2nd parameter: function (func: => T): T = { val txAttribute = new TransactionAttributeWithRollbackRules( propagation,…) val txTemplate = new TransactionTemplate(txManager,txAttribute) txTemplate.execute(func) } Call TransactionTemplate with function (converted to TransactionCallback) and configuration
  • 42. Usage •  Can wrap methods to make them transactional @Component class TxCustomerDAO(dataSource: DataSource) { def save(customer: Customer): Customer = transactional() { jdbcTemplate.update(…); } }
  • 43. Usage •  Can also be used to wrap any code block •  But: No way to make a whole class / system transactional transactional(propagation=Propagation.REQUIRED) { customerDAO.save( Customer(0, "Wolff", "Eberhard", 42.0)) }
  • 45. 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
  • 46. 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() …} }
  • 48. Sum Up •  Scala and Spring are a good match •  Spring is very adaptable •  Dependency Injection –  XML works, some improvements possible –  Annotations and JavaConfig: No problems •  Service Abstraction –  Functions are a good fit •  AOP –  Can work with Scala but not ideal –  Scala can do similar things with functions
  • 49. Potential Improvements •  Dependency Injection –  Support for Scala collections mostly done –  Support for Scala properties (no @BeanProperty) –  Support for Scala Objects aka Singletons –  Conversions for all basic Scala types –  Spring configuration DSL (?) •  Service Abstraction –  Provide implicits for non-JDBC callbacks
  • 50. Potential Improvements •  AOP –  Provide functions for all common aspects besides transaction •  Testing –  Support Scala test frameworks –  http://www.cakesolutions.org/specs2-spring.html
  • 51. Links •  https://github.com/ewolff/scala-spring •  Request for Scala version of Spring (only 16 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
  • 52. Wir suchen Sie als Ø  Software-Architekt (m/w) Ø  Projektleiter (m/w) Ø  Senior Software Engineer (m/w) Ø  Kommen Sie zum Stand und gewinnen Sie ein iPad 2! [email protected] www.AAAjobs.de