Reimeus
Reimeus

Reputation: 159874

Using Spring @Autowired with Scala Trait

I have a simple scenario where I extend a Scala trait as follows:

    trait Vehicle {

      @Autowired
      private var myDistanceLogger: MyDistanceLogger = null

      def travel(miles:Int) = {
        println("travelling " + miles)
        myDistanceLogger.logMiles(miles)
      }
    }

    @Component
    class Truck extends Vehicle {

    }

Even though the Truck package is in Springs component-scan, I am getting a nullpointer exception. All other (non-extended) classes in the package are wired up fine. Any ideas on what is wrong?

Upvotes: 7

Views: 3063

Answers (3)

Petr
Petr

Reputation: 63419

Scala places the annotation on the field, where Spring won't find it. You need to ensure that it is placed on the Scala's internal setter method:

import scala.annotation.meta.setter

@(Autowired @setter)
private var myDistanceLogger: MyDistanceLogger = _

Upvotes: 0

sourcedelica
sourcedelica

Reputation: 24047

I just tested this and it does work - the private var in the trait gets autowired correctly.

When are you calling travel()? That is, are you calling it for sure after all the Spring initialization is complete?

Upvotes: 0

Biju Kunjummen
Biju Kunjummen

Reputation: 49935

This is a little speculation - traits in scala gets translated to a java interface, based on this article. So, your trait:

trait Vehicle {
      @Autowired
      private var myDistanceLogger: MyDistanceLogger = null
}

would get translated to:

public interface Vehicle {
    public MyDistanceLogger myDistanceLogger();
}

and @Autowired would not make sense in a getter, I am guessing this is the reason why this does not get autowired.

Upvotes: 2

Related Questions