Using Spring @Autowired with Scala Trait
dependency-injection, scala, spring
Solution
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.
Problem
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?