I have a simple question, How could I use spring @Autowired on a constructor of this Scala class?
class MessageMBeanExporter(messageDirectory: MessageDirectory) extends MBeanExporter with SmartLifecycle {
.....
}
You can apply @Autowired to constructors as well. A constructor @Autowired annotation indicates that the constructor should be autowired when creating the bean, even if no <constructor-arg> elements are used while configuring the bean in XML file.
So, if more than one Constructor is defined in the Spring bean, then at least one must be annotated with the @Autowired. As of Spring Framework 4.3, an @Autowired annotation on such a constructor is no longer necessary if the target bean only defines one constructor to begin with.
@Autowired annotation can be applied on variables and methods for autowiring byType. We can also use @Autowired annotation on constructor for constructor based spring autowiring. For @Autowired annotation to work, we also need to enable annotation based configuration in spring bean configuration file.
Spring container looks at the beans on which autowire attribute is set constructor in the XML configuration file. It then tries to match and wire its constructor's argument with exactly one of the beans name in the configuration file. If matches are found, it will inject those beans.
I haven't tried it, but according to this and this link, from 2.8+ you could do:
class MessageMBeanExporter @Autowired() (messageDirectory: MessageDirectory) extends MBeanExporter with SmartLifecycle {
.....
}
I've added support for @Autowired on the constructor of a Scala object into the spring-scala project. This is only (at time of writing) in the nightly snapshot.
This allows you to do
@Component
@Autowired
class Service(dep : Dependency) { }
https://github.com/spring-projects/spring-scala
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With