Pages

Showing posts with label SBT. Show all posts
Showing posts with label SBT. Show all posts

Sunday, September 7, 2014

HowTo:: Design patterns with Scala: GoF Structural Pattern Adapter and power of Trait

  
Img.1.:: Parts of Adapter patterns

   In this example I want to show power of trait usage in 2 different ways of Adapter Structural pattern implementations. There are couple of reasons why could be worth to think about the Adapter pattern. Basically the intent is to convert interface of the one type into the interface that client expects to use.
Pattern can be divided into the following parts (Img.1.):
1. Client - is an object that requires functionality provided by Adaptee but it's exposed by Adapter
2. Adapter - is an object that converts the interface expected by the client into the interface provided by Adaptee 
3. Adaptee - is an object that provides the implementation and the interface invoked by the Adapter

in both Adapter examples we do use same Client implementation: 
class Client(service: Service) {
  def doWork = {
    service.invoke
  }
}
and Service trait which defines method process:
trait Service {
  def process(): Unit
}
  Already from the Main Scala Object AdapterTest.scala is noticeable the 1st warm up of the Scala trait power which will be fully exposed by AdaptorTrait latter.
object AdapterTest {

  private val logger = LoggerFactory.getLogger(getClass)

  def main(args: Array[String]) ={
    logger.debug("Test Adapter pattern")
    val adaptor = new AdaptorOne
    val clientWithoutTrait = new Client(adaptor)
    clientWithoutTrait.doWork()

    val adaptorTraitOne = new AdapteeOne with AdaptorTrait
    val adaptorTraitTwo = new AdapteeTwo with AdaptorTrait
    val clientWithTrait1 = new Client(adaptorTraitOne)
    clientWithTrait1.doWork()

    val clientWithTrait2 = new Client(adaptorTraitTwo)
    clientWithTrait2.doWork()
  }

}

1. Object based implementation without trait we do use classical scala class definition of the AdapteeOne that provides implementation to the action() that Client wants.
class AdapteeOne extends Adaptee{
  private val logger = LoggerFactory.getLogger(getClass)
  def action() = { logger.debug("Adaptee One Action One")}
}
  The Adapee trait is used to make code standardised and also to point out limits of the presented Object implementation .
trait Adaptee {
  def action()
}
  Currently has been implemented 1st part of the blog post -> Adapter in the classical object way.

2. trait based approach is inspired by having two, almost same, objects (example: CAR1, CAR2) and both has different implementation of the action() function (example: both cars can ride). We again use AdapteeOne (previously implemented) and we create AdapteeTwo scala class.
class AdapteeTwo extends Adaptee{
  private val logger = LoggerFactory.getLogger(getClass)
  def action() = { logger.debug("Adaptee Two Action")}
}
   Both classes extend Adaptee trait which method is served to the AdaptorTrait that extend the Service (also previously defined)
trait AdaptorTrait extends Service{
  self: Adaptee =>
  def process() = action()
}
   Now we are ready also with 2nd Adapter pattern example usage. Trait usage (AdaptorTrait) allows to be mixed into a type either directly at the type declaration time or an object creation time.  This simply allows latter object behaviour extension. 
Traits go ahead! implementation with them is much easier, readable and extendable  + testable, less code

Tuesday, August 19, 2014

Spring 4 Scala MVC without Web.XML - Tiles3 : WebConfig class configuration with Localisation


Img.1.:: Spring 4 Scala project structure with Tiles 3 and l18n(l10n) 
  Enabling Apache Tiles3 needs little more changes in the project (Img.1.) configuration. The WebConfig scala class needs to extended by WebMvcConfigurerAdapter (already touched in the previous post: Scala Spring 4 MVC without Web.XML configuration with static resources handling). 
  We also define the set of annotations we do need to be scanned over the project package. The reason of such definition is to show possibilities of Scala configuration of the Spring Framework itself.
@Configuration
@ComponentScan(basePackages = Array("miko.scala.helloexample"), useDefaultFilters = false, includeFilters = Array(
  new ComponentScan.Filter(`type` = FilterType.ANNOTATION,
    value = Array(classOf[Controller], classOf[Service]))))
@EnableWebMvc
class WebConfig extends WebMvcConfigurerAdapter{
...
  In WebConfig we do replace @Bean setupViewResolver(), which implements the ViewResolver interface that allows directly resolved symbolic view names,  by getTilesConfigurer @Bean, which provide TilesConfigurer
  The TilesConfigurer class provide the tempting mechanism for web project (application) using JSP and other front-end engines. 
@Bean
def getTilesConfigurer: TilesConfigurer = {
  val configurer:TilesConfigurer = new TilesConfigurer()
  configurer.setCheckRefresh(true)
  configurer.setDefinitions({"/WEB-INF/pages/tiles.xml"})
  configurer
}
 And additionally we have  to define ViewResolver for Tiles by getTilesViewResolver @Bean definition
@Bean
def getTilesViewResolver: ViewResolver = {
  val resolver:TilesViewResolver = new TilesViewResolver()
  resolver.setContentType("text/html")
  resolver
}
The full configuration needs to define and override also couple of other Beans connected with our localisation (l10n/l18n) intent. The final WebConfig Scala class will look in following manner. 
@Configuration
@ComponentScan(basePackages = Array("miko.scala.helloexample"), useDefaultFilters = false, includeFilters = Array(
  new ComponentScan.Filter(`type` = FilterType.ANNOTATION,
    value = Array(classOf[Controller], classOf[Service]))))
@EnableWebMvc
class WebConfig extends WebMvcConfigurerAdapter{

  private val logger = LoggerFactory.getLogger(getClass)

  override def configureDefaultServletHandling(configurer: DefaultServletHandlerConfigurer) = {
    configurer.enable()
  }

  override def addViewControllers(registry: ViewControllerRegistry): Unit ={
    registry.addViewController("/")
  }

  @Bean
  def getTilesViewResolver: ViewResolver = {
    val resolver:TilesViewResolver = new TilesViewResolver()
    resolver.setContentType("text/html")
    resolver
  }

  @Bean
  def getTilesConfigurer: TilesConfigurer = {
    val configurer:TilesConfigurer = new TilesConfigurer()
    configurer.setCheckRefresh(true)
    configurer.setDefinitions({"/WEB-INF/pages/tiles.xml"})
    configurer
  }

  override def addInterceptors(registry:InterceptorRegistry) = {
    val localeChangeInterceptor = new LocaleChangeInterceptor()
    localeChangeInterceptor.setParamName("lang")
    registry.addInterceptor(localeChangeInterceptor)
  }

  /**
   * equivalents for  tags
   * @param registry
   */
  override def addResourceHandlers(registry: ResourceHandlerRegistry) = {
    logger.debug("Resources HANDLER")
    registry.addResourceHandler("/app/**").addResourceLocations("/app/").setCachePeriod(31550522)
    registry.addResourceHandler("/WEB-INF/layouts/**").addResourceLocations("/WEB-INF/layouts/").setCachePeriod(31550522);
    registry.addResourceHandler("/WEB-INF/pages/template/**").addResourceLocations("/WEB-INF/pages/template/").setCachePeriod(31550522);
  }

  @Bean(name = Array("localeResolver"))
  def getLocaleResolver: LocaleResolver = {
    val cookieLocaleResolver: CookieLocaleResolver = new CookieLocaleResolver()
    cookieLocaleResolver.setDefaultLocale(new Locale("en"))
    cookieLocaleResolver
  }

  override def configureContentNegotiation(configurer: ContentNegotiationConfigurer) = {
    configurer.favorPathExtension(true).ignoreAcceptHeader(true)
        .useJaf(false).defaultContentType(MediaType.TEXT_HTML)
        .mediaType("html", MediaType.TEXT_HTML)
        .mediaType("xml", MediaType.APPLICATION_XML)
        .mediaType("json", MediaType.APPLICATION_JSON)
  }

  @Bean(name = Array("messageSource"))
  def getMessageSource: MessageSource = {
    val msgSrc:ReloadableResourceBundleMessageSource = new ReloadableResourceBundleMessageSource()
    msgSrc.setBasename("classpath:/messages/message")
    msgSrc
  }
}
  After having enabled Tiles with l10n/l18n on the back-end side we can move to front-end and tell Tiles which kind of template it should use to display pages correctly to the user (Img.1. ~ project structure). Of course, with CSS or possible JavaScript libraries. 
But I'll do this in next blog post. 
  Now Enjoy configuring your WebConfig scala class. 

project: miko-spring-scala on github

Spring 4 Scala MVC without Web.XML - Tiles3 with SBT Tomcat7 configuration

  In the one of previously published blogposts I've written about Spring Container running on Jetty (Scala Spring 4 MVC without Web.XML configuration with static resources,  update: Scala Spring 4 MVC without Web.XML - logging with Log4j and SLF4j)

  The next example Spring 4 Scala MVC without Web.XML with Apache Tiles3 runs on Tomcat7 using Java Servlet 3.x but before we need to configure SBT to provide us such functionality: 

1. configure project build.sbt file in following example way
libraryDependencies ++= Seq(
  "org.springframework" % "spring-webmvc" % "4.0.6.RELEASE",
  "org.springframework" % "spring-context" % "4.0.6.RELEASE",
  "org.springframework" % "spring-context-support" % "4.0.6.RELEASE",
  "org.apache.tiles" % "tiles-jsp" % "3.0.4",
  "javax.servlet" % "javax.servlet-api" % "3.0.1" % "provided",
  "javax.servlet" % "jstl" % "1.2" % "compile",
  "org.slf4j" % "jcl-over-slf4j" % "1.7.5" ,
  "org.slf4j" % "slf4j-api" % "1.7.5" ,
  "org.slf4j" % "slf4j-log4j12" % "1.7.5",
  "log4j" % "log4j" % "1.2.17" excludeAll(
        ExclusionRule(organization = "com.sun.jdmk"),
        ExclusionRule(organization = "com.sun.jmx"),
        ExclusionRule(organization = "javax.jms")
      ),
  "org.apache.tomcat.embed"% "tomcat-embed-core"% "7.0.40"% "container",
  "org.apache.tomcat.embed"% "tomcat-embed-logging-juli"% "7.0.40"% "container",
  "org.apache.tomcat.embed"% "tomcat-embed-jasper"% "7.0.40"% "container"
)

tomcat(port = 9090)
important part is about tomcat related libraries which allow us:

2. by having running sbt such configuration makes possible to use following command 
container:start
stopping server is by exchanging word after :

Enjoy SBT Tomcat 7 development !

project: miko-spring-scala on github

Thursday, August 14, 2014

Multithreading with Scala and Akka-Actor : PingPong game example

  This small blog post is not only for those who have read/reading cool Scala Cookbook and more specifically chapter about how to use Akka toolkit. Akka with Actors helps to build up highly concurrent, distributed and fault tolerant event-driven application ("we are reactive") on the JVM.

 I'll little modify example which comes from the Scala Cookbook and make new SBT based project out of it to show multi-threading outcome. The build.sbt file:
name := "miko-scala-akka"
version := "1.0"
libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-actor" % "2.4-SNAPSHOT",
  "com.typesafe.akka" %% "akka-testkit" % "2.4-SNAPSHOT",
  "org.slf4j" % "jcl-over-slf4j" % "1.7.7" ,
  "org.slf4j" % "slf4j-api" % "1.7.7" ,
  "org.slf4j" % "slf4j-log4j12" % "1.7.7",
  "org.apache.logging.log4j" % "log4j" % "2.0" excludeAll(
      ExclusionRule(organization = "com.sun.jdmk"),
      ExclusionRule(organization = "com.sun.jmx"),
      ExclusionRule(organization = "javax.jms")
      ),
  "org.scalatest" % "scalatest_2.11" % "2.2.1" % "test",
  "junit" % "junit" % "4.11" % "test"
)
resolvers += "Akka Snapshot Repository" at "http://repo.akka.io/snapshots/"
  Every Actor from Akka toolkit should send immutable messages (note: we will check it). For such purpose is used binary operator "!" after which the message is passed as an argument.
Ping Actor:
class Pong extends Actor{
  val name: String = "pongActor"
  def receive = {
    case PingMessage =>
      println(" pong")
      sender ! PongMessage
    case StopMessage =>
      println(" pong stopped")
      context.stop(self)
  }
}
Pong Actor:
class Pong extends Actor{
  def receive = {
    case PingMessage =>
      println(" pong")
      sender ! PongMessage
    case StopMessage =>
      println(" pong stopped")
      context.stop(self)
  }
}
our Ping and Pong actors are defined but used messages not. We create 4 case object (case object can be serialized, pattern matching support, default implementation of equals and hashCode ...
case object PingMessage {
  println("This is PingMessage")
}
case object PongMessage {
  println("This is PongMessage")
}
case object StartMessage {
  println("This is StartMessage")
}
case object StopMessage {
  println("This is StopMessage")
}
  Now we have everything ready to create final object PingPongTest:
object PingPongTest{
  private val logger = LoggerFactory.getLogger(getClass)
  def main(args: Array[String]): Unit = {
    logger.debug("---PingPong Game Start---")
    val system = ActorSystem("PingPongSystem")
    val pong = system.actorOf(Props[Pong], name = "pong")
    val ping = system.actorOf(Props(new Ping(pong)), name = "ping")

    // Start the game
    ping ! StartMessage
    logger.debug("---PingPong Game Stop---")
    system.shutdown()
  }
}
  The main purpose of updating the PingPong game is to show how Reactive Application (multi-threading) works . The Simple Logging Facade (SLF4j) Logger is used here to hightlight the simple reactive application flow.
DEBUG: miko.scala.akka.pingpong.PingPongTest$ - ---PingPong Game App Start---
This is StartMessage
DEBUG: miko.scala.akka.pingpong.PingPongTest$ - ---PingPong Game App End---
ping
This is PingMessage
 pong
This is PongMessage
ping
 pong
ping
 pong
ping
 pong
ping
 pong
ping
 pong
ping
 pong
ping
This is StopMessage
ping stopped
 pong stopped
  From the file output is visible how exciting multi-threading environment is. The event-driven distributed system design could more fit to the nature reality of the world around us. 
Enjoy with GiTHub example

Design Patterns with Scala: GoF Creational Pattern - Factory Operation (GoF: Factory)

  Factory operation design pattern provides the way how to construct object of the specific type. The intent is to hide an object instantiation from a client which support flexibility in such instantiation process (decide which class will be instantiated).
  Let's show over the simple example how such Factory method deals with the issue of the different type of object creation

  UnivProduct trait is the abstract super type of objects which will be produced by object ProductFactory.
trait UnivProduct {
  val name: String
  val value: Any
}
  By having defined abstraction UnivProduct we can create two concrete classes which can be instantiated by object ProductFactory latter.
UnivProductOne:
case class UnivProductOne(i: Int) extends UnivProduct{
  val name:String = "MyIntegerProduct"
  val value:Int = i

  override def toString = "name= "+ name +" val= " + value
}
  UnivProductTwo:
case class UnivProductTwo(s: String) extends UnivProduct {
  val name:String = "MyStringProduct"
  val value:String = s

  override def toString = "name= "+ name +" val= " + value
}
  Now we create FactoryOperation trait which provides us the specification of the methods (behaviour) that ProductFactory object must provide.
trait FactoryOperation {
  def create(a: Any): UnivProduct
}
  Then we define ProductFactory object in following way:
object ProductFactory extends FactoryOperation{
  implicit def create(a: Any): UnivProduct = a match {
    case s: String => UnivProductTwo(s)
    case i: Int => UnivProductOne(i)
  }
}
which simplifies the access to the Factory with limiting ability to employ different Product Factories (can by fixed by implementing factory of factories). The methods create in ProductFactory object is marked as implicit (inserted by compiler).
  At the end we create the singleton Scala object FactoryTest to put all together and see the result.
object FactoryTest {
  private val logger = LoggerFactory.getLogger(getClass)

  def main(args: Array[String]): Unit = {
    val productA: UnivProduct = ProductFactory.create("Mirage")
    logger.debug("ProductA name= " + productA.name + " value= " + productA.value)
    logger.debug("ProductA toString= " + productA)

    val productB:UnivProduct = ProductFactory.create(22)
    logger.debug("ProductB name= " + productB.name + " value= " + productB.value)
    logger.debug("ProductB toString= " + productB)

    val productC: UnivProduct = "Tanja"
    logger.debug("ProductC name= " + productC.name + " value= " + productC.value)
    logger.debug("ProductC toString= " + productC)

    val productD: UnivProduct = 5
    logger.debug("ProductD name= " + productD.name + " value= " + productD.value)
    logger.debug("ProductD toString= " + productD)
  }
}

expected output:
ProductA name= MyStringProduct value= Mirage
ProductA toString= name= MyStringProduct val= Mirage
ProductB name= MyIntegerProduct value= 22
ProductB toString= name= MyIntegerProduct val= 22
ProductC name= MyStringProduct value= Tanja
ProductC toString= name= MyStringProduct val= Tanja
ProductD name= MyIntegerProduct value= 5
ProductD toString= name= MyIntegerProduct val= 5
  Enjoy using Factory Operation Design patter and my GiTHub is still in progress as I want to much more to share.

Tuesday, August 12, 2014

Design Patterns with Scala: Fundamental Pattern - Marker Trait

The Marker Trait pattern is the fundamental pattern in Scala. The main point is in using trait which are free on any declaration (method, function etc.) to indicated additional type logical semantic within the domain. The Marker Trait pattern adds ability to be treated as part of Scala type system. For example such approach is used in scala.Mutable or scala.Immutable traits to distinguish between them to indicate the semantic.

In the example we define trait MarkerTrait which will be mixed into any other classes
trait MarkerTrait {
}
Then we define two example classes with some methods.
ClassOne:
case class ClassOne(id: String) extends MarkerTrait{
  def name: String = "ClassOne ID= " + id
}
and ClassTwo:
case class ClassTwo(value: String) extends MarkerTrait{
  def name: String = "ClassTwo value= " + value
}

After having defined classes we define the universal printer UnivPrinter object (note: is singleton) with methods print where MarkerTrait can be passed and printed out.
object UnivPrinter {
  private val logger = LoggerFactory.getLogger(getClass)
  def print(o: MarkerTrait) = {
    logger.debug("MarkerTrait " + o)
  }
}
As the last step we can define object MarkerTest with main method. Inside the main method we instantiate our two classes (ClassOne, ClassTwo) and pass them to the UnivPrinter.print method
object MarkerTest {
  private val logger = LoggerFactory.getLogger(getClass)
  def main(args: Array[String]): Unit = {
    logger.debug("Marker Trait Fundamental Pattern")
    UnivPrinter.print(new ClassOne("ID"))
    UnivPrinter.print(new ClassTwo("Value"))
  }
}
As the alternative connection to the Java world can be taken Annotation. The Annotation is not part of the Scala type system. The trait itself is much powerful in Scala then interfaces in Java as trait can define additional behaviour. This trait power can cause some implementation mixing issues.


Design Patterns with Scala: Creational Pattern - Singleton

  The singleton design pattern is probably most known one from GoF Creational Pattern list. The singleton pattern says that only one instance of the specific class will be ever created per ClassLoader. 
ps: "This is little bit different in Spring Framework. The Spring Singleton is unique per Spring IoC container per bean which means single instance per Spring context. It also means it's not the singleton pattern" (note) 

  In Java is quite easy to create Singleton pattern and as the whole world is Multi-Threading I'd recommend to reflect this fact and use any of thread-safe implementation double-check-locking or volatile keyword (value is taken then from the main memory and follows happens-before relationship on visibility of among multiple threads). 
The initialisation process is necessary only when the instance is created (by calling getInstance() method). 

In Scala is situation less complicated because in Scala there are no static members (ps: static members concept in Java goes a bit against the OOP principle where everything is an object). Scala has singleton objects done by usage of keyword object
object Singleton {
  val id = "singleton"
  override def toString = "this is the Singleton object"
}
The example shows how easy it is to achieve the singleton pattern is in Scala.
More patterns are on the way and they will be soon on my github soon.

Saturday, August 9, 2014

update: Scala Spring 4 MVC without Web.XML - logging with Log4j and SLF4j

  This is small update to the previous blogpost (Scala Spring 4 MVC without Web.XML). It shows how to add commonly used Java libraries into the Spring scala project. 
In this example is log4j 1.x used but any change can be easily done when you clone my git hub project. Basically this post shows how to add commonly used libraries into any scala project.

  Let's import last version of Simple Logging Facede 4 Java (SLF4J) and not thin Scala (SLF4S) wrapper to it which is written by Heiko Seeberger.

  We do whole example update in several steps:
1. we need to update our build.sbt file and import appropriate library dependencies
libraryDependencies ++= Seq(
  "org.springframework" % "spring-webmvc" % "4.0.6.RELEASE",
  "org.springframework" % "spring-context" % "4.0.6.RELEASE",
  "org.springframework" % "spring-context-support" % "4.0.6.RELEASE",
  "javax.servlet" % "javax.servlet-api" % "3.0.1" % "provided",
  "javax.servlet" % "jstl" % "1.2" % "compile",
  
  "org.slf4j" % "jcl-over-slf4j" % "1.7.5" ,
  "org.slf4j" % "slf4j-api" % "1.7.5" ,
  "org.slf4j" % "slf4j-log4j12" % "1.7.5",
  "log4j" % "log4j" % "1.2.17" excludeAll(
        ExclusionRule(organization = "com.sun.jdmk"),
        ExclusionRule(organization = "com.sun.jmx"),
        ExclusionRule(organization = "javax.jms")
      ),
  
  "org.eclipse.jetty" % "jetty-webapp" % "9.1.0.v20131115" % "container, compile",
  "org.eclipse.jetty" % "jetty-jsp" % "9.1.0.v20131115" % "container"
)

2. in the resources folder we configure log4j logger and some properties (Img.1.). Example configuration is done for Tomcat server.
Img.1.:: Spring 4 Scala project structure with logging configuration
 3. org.slf4j.LoggerFactory is now available for import into HelloExampleController and to log Controller behaviour.
...
private val logger = LoggerFactory.getLogger(getClass)

@RequestMapping(method =  Array(RequestMethod.GET))
def hello( model: Model) = {
  logger.info("Info Test")
  logger.debug("Debug Test")
  logger.error("Error Test")
...

All code is available over my github for testing. Small hint could be Log4j 2 which promises significant improvements over its predecessor, logback and etc.
Enjoy!


Friday, August 8, 2014

HowTo:: Scala Spring 4 MVC without Web.XML configuration with static resources handling

This blog post is fully focused on Scala language and how to use it for Spring 4 based application development. I'll  modify application I've used over previous blog post series ("Spring4Netty without Web.XML configuration on Java 8.."). 

  Although Spring Framework is so popular in the Java land, there is no reason why not to use Scala language for the EE application development. 
In case when the Applicaiton front-end uses popular AngularJS Framework I personally find Scala usage much "easier" (ps: still lot of work :) and comfortable to understand back-end and front-end functionality as javascript uses callbacks. 

for building new Spring4 Scala application we use following tools: 
of course Jetty server can be change to the Tomcat one. 
  Whole sample application has been developed in IntelliJ IDEA 13.x IDE. 
After we have created the SBT project under IntelliJ we need to import some plugins.
Img.1.:: SBT Project Structure - plugins.sbt
  To import them we change sbt plugins setup by modifying appropriate file (Img.1.) in the following manner. 
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "1.0.0-M4")

addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.6.0")
  We have now added two plugins  xsbt-web-plugin and sbt-idea.  The xsbt-web-plugin is used for building web enterprise application. Both of them are extensions to SBT building tool.

  Next step is to add necessary libraries dependences into the build.sbt file. As we want to link also static resources, for the front-end development, the number of needed libraries will be bigger. 
  The build.sbt file will look after our modification like following example.
name := "miko-spring-scala"

version := "1.0"

scalaVersion := "2.10.3"

libraryDependencies ++= Seq(
  "org.springframework" % "spring-webmvc" % "4.0.6.RELEASE",
  "org.springframework" % "spring-context" % "4.0.6.RELEASE",
  "org.springframework" % "spring-context-support" % "4.0.6.RELEASE",
  "javax.servlet" % "javax.servlet-api" % "3.0.1" % "provided",
  "javax.servlet" % "jstl" % "1.2" % "compile",
  "org.eclipse.jetty" % "jetty-webapp" % "9.1.0.v20131115" % "container, compile",
  "org.eclipse.jetty" % "jetty-jsp" % "9.1.0.v20131115" % "container"
)

jetty(port = 9090)
here is visible which kind of servlet engine provider will be used (in case of Tomcat change jetty() to tomcat()). 

  When the SBT application is ready we will use commands to start/stop it.
... SBT console ...
container:start

container:stop
...
  All libraries and plugins are ready and we can start building Spring4 Scala Application without using Web.XML and with linked static resources for the next front-end development. Web.xml file will look almost empty in contracts to XML configuration.
...
Miko Scala Spring 4 - Example without Web.xml 
...
  The application package structure is very similar to the previous ones. I want to keep consistency and get possibility to have the reference to the Java implementation (Img.2.) in case of possible comparison.
Img.2.:: Example Spring4 Scala application packages structure

Now I simply turn the Java into the Scala in several steps

1. Scala WebConfig will look like following

..
@Configuration
@ComponentScan(basePackages = Array("miko.scala.helloexample"))
@EnableWebMvc
class WebConfig extends WebMvcConfigurerAdapter{

  override def addResourceHandlers(registry: ResourceHandlerRegistry) = {
    registry.addResourceHandler("/app/**").addResourceLocations("/app/").setCachePeriod(31550522)
  }

  override def configureDefaultServletHandling(configurer: DefaultServletHandlerConfigurer) = {
    configurer.enable()
  }

  @Bean
  def viewResolver = {
    val viewResolver = new InternalResourceViewResolver
    viewResolver.setViewClass(classOf[JstlView])
    viewResolver.setPrefix("/WEB-INF/pages/")
    viewResolver.setSuffix(".jsp")
    viewResolver
  }
}
2. Scala WebInitializer which help us setup ServletContext at the starup 
class WebInitializer extends WebApplicationInitializer{

  override def onStartup(servletContext: ServletContext) = {
    val ctx = new AnnotationConfigWebApplicationContext
    ctx.register(classOf[WebConfig])

    ctx.setConfigLocation("META-INF/spring/app-spring-scala.xml")

    val servlet: Dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx))
    servlet.addMapping("/")
    servlet.setLoadOnStartup(1)
  }
}
3. Scala HelloExampleController class annotated by @Contoller annotation. The Annotation takes care about HttpServletRequest and Responses. This example controller also shows how Services are @Autowired when Scala language is used. 
@Controller
@RequestMapping(Array("/"))
class HelloExampleController @Autowired() (exampleService: ExampleService, exampleImportService: ExampleImportService){

  @RequestMapping(method =  Array(RequestMethod.GET))
  def hello( model: Model) = {
    model.addAttribute("message", "Here is Scala with ServiceName = " + exampleService.serviceName)
    model.addAttribute("importMessage", "Here is Scala with ServiceImportName = " + exampleImportService.name)
    "hello"
  }
}
4. Scala Example...Services used by HelloExampleController are done over quite powerful Traits implementation. Traits are very similar to Java Interfaces but they allows partial implementation which makes them much more powerful (out of blogpost scope ;).  
trait ExampleImportService {
  def name: String
}
-----
class ExampleImportServiceImpl extends ExampleImportService{
  override def name: String = "Imported service over XML"
}

after all those steps we've ready Scala Spring 4 application to test. We've also source code to compare with previous Java8 implementation. Scala does the great work because thinking in functions and callbacks intentions makes whole development more strait forward. 
Enjoy sample application ! (GitHub miko-spring-scala)