Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 260
Reimeus Avatar asked May 29 '12 00:05

Reimeus


1 Answers

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.

like image 67
Biju Kunjummen Avatar answered Sep 18 '22 13:09

Biju Kunjummen