Java – How to effectively use Scala in a Spring MVC project

java, maven, scala, spring

I want to create a multi-module (maven) spring MVC application, with modules like:

webpersistance (hibernate)core (general libs)modelsjob-server (queue based jobs)services (business logic)

Now to use Scala in this project, can I write scala everywhere without any problems?
Or should I use scala for my services module, and java for the web module?

I know hibernate will have to be in java.

Thoughts? Advice?

Are there any issues to look out for? Is this a good idea? Will I have to hack certain parts to glue them together?

Best Solution

Yes, you can use Scala for both your Spring MVC code and your Hibernate classes.

Here is an example of a Spring MVC Controller in Scala taken from one of my projects:

@Controllerclass HomeController {  val log: Logger = LoggerFactory.getLogger(this.getClass.getName)  @RequestMapping(Array("/"))  def home: String = {    log.debug("HomeController::home")    "home/home"  }}

And an example of a Hibernate domain class. Note the use of private Java collection classes for Hibernate adapted by public Scala collection classes for users of the class (helped by Scala's JavaConversions class).

@Entityclass Role {  @Id @GeneratedValue  var id: Long = _  @Index(name="role_name")  var name: String = _  var created_at: Date = _  var updated_at: Date = _    @ManyToMany  private var sub_role: java.util.Set[Role] = _  def subRoles: Set[Role] = {    if (sub_role == null) sub_role = new java.util.HashSet[Role]    sub_role  }  @ManyToMany  private var permission: java.util.Set[Permission] = _  def permissions: Set[Permission] = {    if (permission == null) permission = new java.util.HashSet[Permission]    permission  }}

The only thing I've found that I've had to use Java for is writing @Retention(RUNTIME) annotations (for JSR-303 validations).

I use Maven and the maven-scala-plugin with mixed Java/Scala projects.