Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency injection, Scala and Spring

I love the concept of DI and loosely coupled system, a lot. However, I found tooling in Spring lacking at best. For example, it's hard to do "refactoring", e.g. to change a name of a bean declared in Spring. I'm new to Spring, so I would be missing something. There is no compiling time check etc.

My question is why do we want to use XML to store the configuration? IMO, the whole idea of Spring (IoC part) is to force certain creational pattern. In the world of gang-of-four patterns, design patterns are informative. Spring (and other DIs) on the other hand, provides very prescribed way how an application should be hooked up with individual components.

I have put Scala in the title as well as I'm learning it. How do you guys think to create a domain language (something like the actor library) for dependency ingestion. Writing the actual injection code in Scala itself, you get all the goodies and tooling that comes with it. Although application developers might as well bypass your framework, I would think it's relatively easy to standard, such as the main web site/app will only load components of certain pattern.

like image 544
Xian Xu Avatar asked Aug 11 '10 23:08

Xian Xu


2 Answers

There's a good article on using Scala together with Spring and Hibernate here.

About your question: you actually can use annotations. It has some advantages. XML, in turn, is good beacause you don't need to recompile files, that contain your injection configs.

like image 94
George Avatar answered Oct 23 '22 10:10

George


There is an ongoing debate if Scala needs DI. There are several ways to "do it yourself", but often this easy setup is sufficient:

//the class that needs injection
abstract class Foo {
  val injectMe:String
  def hello = println("Hello " + injectMe)
}

//The "binding module"
trait Binder {
  def createFooInstance:Foo
}

object BinderImpl extends Binder {
  trait FooInjector {
    val injectMe = "DI!"   
  }

  def createFooInstance:Foo = new Foo with FooInjector
}

//The client
val binder:Binder = getSomehowTheRightBinderImpl  //one way would be a ServiceLoader
val foo = binder.createFooInstance
foo.hello
//--> Hello DI!

For other versions, look here for example.

like image 31
Landei Avatar answered Oct 23 '22 12:10

Landei