Using Spring @ Used with Scala Trait

I have a simple scenario where I extend the Scala tag 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 {

    }

Despite the fact that the Truck package is in the component scan of Springs, I get a nullpointer exception. All other (non-extended) classes in the package are perfectly connected. Any ideas on what's wrong?

+5
source share
3 answers

This is a small assumption - the features in scala are converted to a java interface based on this article. So your trait:

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

will be translated into:

public interface Vehicle {
    public MyDistanceLogger myDistanceLogger();
}

and it @Autowireddoesn’t make sense in getter, I assume that this is the reason why this does not work out automatically.

+1
source

, - var .

()? , Spring?

0

Scala places the annotation in a field where Spring won't find it. You need to make sure that it is placed in the method

import scala.annotation.meta.setter

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

All Articles